List of usage examples for com.google.common.collect Multiset count
int count(@Nullable Object element);
From source file:BibTex.IOmethods.java
public void writeJournalsAndTheirCategories(Set<BibTexRef> refs, Integer minNumber) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(folder + "journals and their categories.csv")); // BufferedWriter bwJournals = new BufferedWriter(new FileWriter(folder + "journals.csv")); StringBuilder sb = new StringBuilder(); String sep = "|"; //creation of convenient data structures for I/O Map<String, Multiset<String>> journalsAndTheirCategories = new HashMap(); Multiset journals = HashMultiset.create(); JournalAbbreviationsMapping jmap = new JournalAbbreviationsMapping(); jmap.loadMap();// w w w . ja va 2s . com for (BibTexRef ref : refs) { Set<Category> categories = ref.getCategories(); String title = ref.getJournal(); if (title == null || title.isEmpty()) { continue; } title = title.toLowerCase(); Set<String> abbrev = (Set<String>) jmap.getJournalsToAbbrev().get(title); if (abbrev == null || abbrev.isEmpty()) { abbrev = new HashSet(); abbrev.add(title); } String abbreviation = abbrev.iterator().next(); journals.add(abbreviation); if (!journalsAndTheirCategories.containsKey(abbreviation)) { Multiset<String> cats = HashMultiset.create(); journalsAndTheirCategories.put(abbreviation, cats); } for (Category category : categories) { journalsAndTheirCategories.get(abbreviation).add(category.getCategoryName()); } } for (String journal : journalsAndTheirCategories.keySet()) { if (journals.count(journal) < minNumber) { continue; } for (String category : journalsAndTheirCategories.get(journal).elementSet()) { sb.append(journal).append(sep).append(category).append(sep) .append(journalsAndTheirCategories.get(journal).count(category)).append("\n"); } } bw.write(sb.toString()); bw.close(); // sb = new StringBuilder(); // for (String journal : journalsAndTheirCategories.keySet()) { // Set<String> abbrev = (Set<String>) jmap.getJournalsToAbbrev().get(journal); // if (abbrev == null || abbrev.isEmpty()) { // abbrev = new HashSet(); // abbrev.add(journal); // } // sb.append(journal).append(sep).append(abbrev.iterator().next()).append("\n"); // } // bwJournals.write(sb.toString()); // bwJournals.close(); }
From source file:org.dllearner.algorithms.pattern.PatternBasedAxiomLearningAlgorithm.java
private Set<OWLAxiom> applyPattern(OWLAxiom pattern, OWLClass cls, Model fragment) { Map<OWLAxiom, Score> axioms2Score = new HashMap<>(); OWLClassExpression patternSubClass = null; OWLClassExpression patternSuperClass = null; if (pattern.isOfType(AxiomType.EQUIVALENT_CLASSES)) { Set<OWLSubClassOfAxiom> subClassOfAxioms = ((OWLEquivalentClassesAxiom) pattern) .asOWLSubClassOfAxioms(); for (OWLSubClassOfAxiom axiom : subClassOfAxioms) { if (!axiom.getSubClass().isAnonymous()) { patternSubClass = axiom.getSubClass(); patternSuperClass = axiom.getSuperClass(); break; }//from w ww. j a va 2 s. co m } } else if (pattern.isOfType(AxiomType.SUBCLASS_OF)) { patternSubClass = ((OWLSubClassOfAxiom) pattern).getSubClass(); patternSuperClass = ((OWLSubClassOfAxiom) pattern).getSuperClass(); } else { logger.warn("Pattern " + pattern + " not supported yet."); return Collections.emptySet(); } Set<OWLEntity> signature = patternSuperClass.getSignature(); signature.remove(patternSubClass.asOWLClass()); Query query = converter.asQuery("?x", dataFactory.getOWLObjectIntersectionOf(cls, patternSuperClass), signature); logger.info("Running query\n" + query); Map<OWLEntity, String> variablesMapping = converter.getVariablesMapping(); org.apache.jena.query.ResultSet rs = QueryExecutionFactory.create(query, fragment).execSelect(); QuerySolution qs; Set<String> resources = new HashSet<>(); Multiset<OWLAxiom> instantiations = HashMultiset.create(); while (rs.hasNext()) { qs = rs.next(); resources.add(qs.getResource("x").getURI()); // get the IRIs for each variable Map<OWLEntity, IRI> entity2IRIMap = new HashMap<>(); entity2IRIMap.put(patternSubClass.asOWLClass(), cls.getIRI()); boolean skip = false; for (OWLEntity entity : signature) { String var = variablesMapping.get(entity); if (qs.get(var) == null) { logger.warn("Variable " + var + " is not bound."); skip = true; break; } if (qs.get(var).isLiteral()) { skip = true; break; } Resource resource = qs.getResource(var); if (entity.isOWLObjectProperty() && resource.hasURI(RDF.type.getURI())) { skip = true; break; } entity2IRIMap.put(entity, IRI.create(resource.getURI())); } if (!skip) { // instantiate the pattern OWLObjectDuplicator duplicator = new OWLObjectDuplicator(entity2IRIMap, dataFactory); OWLAxiom patternInstantiation = duplicator.duplicateObject(pattern); instantiations.add(patternInstantiation); } } // compute the score int total = resources.size(); for (OWLAxiom axiom : instantiations.elementSet()) { int frequency = instantiations.count(axiom); // System.out.println(axiom + ":" + frequency); Score score = computeScore(total, Math.min(total, frequency)); axioms2Score.put(axiom, score); } return asAnnotatedAxioms(axioms2Score); }
From source file:BibTex.IOmethods.java
public void writeTopContributorByCategoryToFile(Set<BibTexRef> refs) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(folder + "top contributors per categories.csv")); StringBuilder sb = new StringBuilder(); String sep = "|"; //creation of 2 convenient data structures for I/O Map<String, Multiset<Author>> categoriesToAuthors = new TreeMap(); List<String> categoryNames = new ArrayList(); for (BibTexRef ref : refs) { Set<Category> categories = ref.getCategories(); for (Category category : categories) { if (!categoryNames.contains(category.getCategoryName())) { categoryNames.add(category.getCategoryName()); }/*from ww w .j a va 2 s . com*/ if (categoriesToAuthors.containsKey(category.getCategoryName())) { categoriesToAuthors.get(category.getCategoryName()).addAll(ref.getAuthors()); } else { Multiset<Author> authorsForOneCategory = HashMultiset.create(); authorsForOneCategory.addAll(ref.getAuthors()); categoriesToAuthors.put(category.getCategoryName(), authorsForOneCategory); } } } Collections.sort(categoryNames); //writing of the first line of the csv: headers of the categories. for (String categoryName : categoryNames) { sb.append(categoryName); sb.append(sep); } sb.append("\n"); //writing of all subsequent lines: one per year int countCategoriesdone = 0; boolean continueLoop = true; while (continueLoop) { for (Iterator<String> it = categoriesToAuthors.keySet().iterator(); it.hasNext();) { String category = it.next(); Multiset<Author> authorsForOneCategory = categoriesToAuthors.get(category); Iterator<Author> authorsIterator = Multisets.copyHighestCountFirst(authorsForOneCategory) .elementSet().iterator(); if (authorsIterator.hasNext()) { Author author = authorsIterator.next(); sb.append(author.getFullname()).append("(").append(authorsForOneCategory.count(author)) .append(")").append(sep); authorsForOneCategory.remove(author, authorsForOneCategory.count(author)); } else { sb.append(sep); } } sb.append("\n"); for (String cat : categoriesToAuthors.keySet()) { if (categoriesToAuthors.get(cat).isEmpty()) { countCategoriesdone++; } } if (countCategoriesdone == categoryNames.size()) { continueLoop = false; } else { countCategoriesdone = 0; } } bw.write(sb.toString()); bw.close(); }
From source file:BibTex.IOmethods.java
public void writeJournalsPerCategories(Set<BibTexRef> refs) throws IOException { JournalAbbreviationsMapping jmap = new JournalAbbreviationsMapping(); jmap.loadMap();//from w w w.j a va 2s. c o m BufferedWriter bw = new BufferedWriter(new FileWriter(folder + "journals per categories.csv")); StringBuilder sb = new StringBuilder(); String sep = "|"; //creation of 2 convenient data structures for I/O Map<String, Multiset<String>> categoriesToJournals = new TreeMap(); List<String> categoryNames = new ArrayList(); for (BibTexRef ref : refs) { Set<Category> categories = ref.getCategories(); String title = ref.getJournal(); if (title == null || title.isEmpty()) { continue; } title = title.toLowerCase(); Set<String> abbrev = (Set<String>) jmap.getJournalsToAbbrev().get(title); if (abbrev == null || abbrev.isEmpty()) { abbrev = new HashSet(); abbrev.add(title); } String abbreviation = abbrev.iterator().next(); for (Category category : categories) { if (!categoryNames.contains(category.getCategoryName())) { categoryNames.add(category.getCategoryName()); } if (categoriesToJournals.containsKey(category.getCategoryName())) { categoriesToJournals.get(category.getCategoryName()).add(abbreviation); } else { Multiset<String> journalsForOneCategory = HashMultiset.create(); journalsForOneCategory.add(abbreviation); categoriesToJournals.put(category.getCategoryName(), journalsForOneCategory); } } } Collections.sort(categoryNames); //writing of the first line of the csv: headers of the categories. for (String categoryName : categoryNames) { sb.append(categoryName); sb.append(sep); } sb.append("\n"); //writing of all subsequent lines: one per year int countCategoriesdone = 0; boolean continueLoop = true; while (continueLoop) { for (Iterator<String> it = categoriesToJournals.keySet().iterator(); it.hasNext();) { String category = it.next(); Multiset<String> journalsForOneCategory = categoriesToJournals.get(category); Iterator<String> journalsIterator = Multisets.copyHighestCountFirst(journalsForOneCategory) .elementSet().iterator(); if (journalsIterator.hasNext()) { String journal = journalsIterator.next(); sb.append(journal).append(" (").append(journalsForOneCategory.count(journal)).append(")") .append(sep); journalsForOneCategory.remove(journal, journalsForOneCategory.count(journal)); } else { sb.append(sep); } } sb.append("\n"); for (String cat : categoriesToJournals.keySet()) { if (categoriesToJournals.get(cat).isEmpty()) { countCategoriesdone++; } } if (countCategoriesdone == categoryNames.size()) { continueLoop = false; } else { countCategoriesdone = 0; } } bw.write(sb.toString()); bw.close(); }
From source file:buildcraft.transport.Pipe.java
private void resolveActions() { if (!hasGate()) return;/*from ww w . j ava 2 s .c o m*/ boolean oldBroadcastRedstone = broadcastRedstone; boolean[] oldBroadcastSignal = broadcastSignal; broadcastRedstone = false; broadcastSignal = new boolean[] { false, false, false, false }; // Tell the gate to prepare for resolving actions. (Disable pulser) gate.startResolution(); HashMap<Integer, Boolean> actions = new HashMap<Integer, Boolean>(); Multiset<Integer> actionCount = HashMultiset.create(); // Computes the actions depending on the triggers for (int it = 0; it < 8; ++it) { ITrigger trigger = activatedTriggers[it]; IAction action = activatedActions[it]; ITriggerParameter parameter = triggerParameters[it]; if (trigger != null && action != null) { actionCount.add(action.getId()); if (!actions.containsKey(action.getId())) { actions.put(action.getId(), isNearbyTriggerActive(trigger, parameter)); } else if (gate.getConditional() == GateConditional.AND) { actions.put(action.getId(), actions.get(action.getId()) && isNearbyTriggerActive(trigger, parameter)); } else { actions.put(action.getId(), actions.get(action.getId()) || isNearbyTriggerActive(trigger, parameter)); } } } // Activate the actions for (Integer i : actions.keySet()) if (actions.get(i)) { // Custom gate actions take precedence over defaults. if (gate.resolveAction(ActionManager.actions[i], actionCount.count(i))) { continue; } if (ActionManager.actions[i] instanceof ActionRedstoneOutput) { broadcastRedstone = true; } else if (ActionManager.actions[i] instanceof ActionSignalOutput) { broadcastSignal[((ActionSignalOutput) ActionManager.actions[i]).color.ordinal()] = true; } else { for (int a = 0; a < container.tileBuffer.length; ++a) if (container.tileBuffer[a].getTile() instanceof IActionReceptor) { IActionReceptor recept = (IActionReceptor) container.tileBuffer[a].getTile(); recept.actionActivated(ActionManager.actions[i]); } } } actionsActivated(actions); if (oldBroadcastRedstone != broadcastRedstone) { container.scheduleRenderUpdate(); updateNeighbors(true); } for (int i = 0; i < oldBroadcastSignal.length; ++i) if (oldBroadcastSignal[i] != broadcastSignal[i]) { // worldObj.markBlockNeedsUpdate(xCoord, yCoord, zCoord); container.scheduleRenderUpdate(); updateSignalState(); break; } }
From source file:com.palantir.atlasdb.keyvalue.impl.SweepStatsKeyValueService.java
private void flushWrites(Multiset<String> writes, Set<String> clears) { if (writes.isEmpty() && clears.isEmpty()) { log.debug("No writes to flush"); return;//from w w w . j av a2s . c om } log.debug("Flushing stats for {} writes and {} clears", writes.size(), clears.size()); log.trace("Flushing writes: {}", writes); log.trace("Flushing clears: {}", clears); try { Set<String> tableNames = Sets.difference(writes.elementSet(), clears); Iterable<byte[]> rows = Collections2.transform(tableNames, Functions .compose(Persistables.persistToBytesFunction(), SweepPriorityRow.fromFullTableNameFun())); Map<Cell, Value> oldWriteCounts = delegate().getRows(SWEEP_PRIORITY_TABLE, rows, SweepPriorityTable.getColumnSelection(SweepPriorityNamedColumn.WRITE_COUNT), Long.MAX_VALUE); Map<Cell, byte[]> newWriteCounts = Maps.newHashMapWithExpectedSize(writes.elementSet().size()); byte[] col = SweepPriorityNamedColumn.WRITE_COUNT.getShortName(); for (String tableName : tableNames) { Preconditions.checkState(!tableName.startsWith(AtlasDbConstants.NAMESPACE_PREFIX), "The sweep stats kvs should wrap the namespace mapping kvs, not the other way around."); byte[] row = SweepPriorityRow.of(tableName).persistToBytes(); Cell cell = Cell.create(row, col); Value oldValue = oldWriteCounts.get(cell); long oldCount = oldValue == null || oldValue.getContents().length == 0 ? 0 : SweepPriorityTable.WriteCount.BYTES_HYDRATOR.hydrateFromBytes(oldValue.getContents()) .getValue(); long newValue = clears.contains(tableName) ? writes.count(tableName) : oldCount + writes.count(tableName); log.debug("Sweep priority for {} has {} writes (was {})", tableName, newValue, oldCount); newWriteCounts.put(cell, SweepPriorityTable.WriteCount.of(newValue).persistValue()); } long timestamp = timestampService.getFreshTimestamp(); // Committing before writing is intentional, we want the start timestamp to // show up in the transaction table before we write do our writes. commit(timestamp); delegate().put(SWEEP_PRIORITY_TABLE, newWriteCounts, timestamp); } catch (RuntimeException e) { Set<String> allTableNames = delegate().getAllTableNames(); if (!allTableNames.contains(SWEEP_PRIORITY_TABLE) || !allTableNames.contains(TransactionConstants.TRANSACTION_TABLE)) { // ignore problems when sweep or transaction tables don't exist log.warn("Ignoring failed sweep stats flush due to {}", e.getMessage(), e); } log.error("Unable to flush sweep stats for writes {} and clears {}: {}", writes, clears, e.getMessage(), e); throw e; } }
From source file:google.registry.batch.DeleteContactsAndHostsAction.java
@Override public void run() { LeaseOptions options = LeaseOptions.Builder.withCountLimit(maxLeaseCount()).leasePeriod(LEASE_MINUTES, MINUTES);/*from w w w .j a v a 2s. c om*/ List<TaskHandle> tasks = queue.leaseTasks(options); if (tasks.isEmpty()) { response.setPayload("No contact/host deletion tasks in pull queue."); return; } Multiset<String> kindCounts = HashMultiset.create(2); ImmutableList.Builder<DeletionRequest> builder = new ImmutableList.Builder<>(); ImmutableList.Builder<Key<? extends EppResource>> resourceKeys = new ImmutableList.Builder<>(); final List<TaskHandle> tasksToDelete = new ArrayList<>(); for (TaskHandle task : tasks) { try { Optional<DeletionRequest> deletionRequest = DeletionRequest.createFromTask(task, clock.nowUtc()); if (deletionRequest.isPresent()) { builder.add(deletionRequest.get()); resourceKeys.add(deletionRequest.get().key()); kindCounts.add(deletionRequest.get().key().getKind()); } else { tasksToDelete.add(task); } } catch (Exception e) { logger.severefmt(e, "Could not parse async deletion request, delaying task for a day: %s", task); // Grab the lease for a whole day, so that it won't continue throwing errors every five // minutes. queue.modifyTaskLease(task, 1L, DAYS); } } deleteTasksWithRetry(tasksToDelete); ImmutableList<DeletionRequest> deletionRequests = builder.build(); if (deletionRequests.isEmpty()) { logger.info("No asynchronous deletions to process because all were already handled."); response.setPayload("All requested deletions of contacts/hosts have already occurred."); } else { logger.infofmt("Processing asynchronous deletion of %d contacts and %d hosts: %s", kindCounts.count(KIND_CONTACT), kindCounts.count(KIND_HOST), resourceKeys.build()); runMapreduce(deletionRequests); } }
From source file:org.splevo.ui.refinementbrowser.ArgoUMLVariantScanHandler.java
private void scanForIncludedFeatures(List<VariationPoint> vps) { Multiset<String> identifiedFeatues = HashMultiset.create(); List<String> errors = Lists.newArrayList(); for (VariationPoint vp : vps) { Set<SoftwareElement> elements = getNotLeadingImplementingElements((VariationPoint) vp); if (elements.size() == 0) { identifiedFeatues.add("{NONE}"); }// ww w . j a v a 2s.c o m for (SoftwareElement element : elements) { SourceLocation sourceLocation = element.getSourceLocation(); String path = sourceLocation.getFilePath(); List<String> lines = null; try { lines = FileUtils.readLines(new File(path)); } catch (IOException e) { e.printStackTrace(); continue; } int markerLineIndex = getMarkerLineIndex(vp, sourceLocation, lines); if (markerLineIndex == -1) { errors.add("No marker found for " + path.substring(path.length() - 20)); continue; } String featureId = getFeatureId(lines, markerLineIndex); if (isMarkerLine(lines, markerLineIndex - 1)) { featureId = getFeatureId(lines, markerLineIndex - 1) + " + " + featureId; } else if (isMarkerLine(lines, markerLineIndex + 1)) { featureId += " + " + getFeatureId(lines, markerLineIndex + 1); } identifiedFeatues.add(featureId); } } if (errors.size() > 0) { MessageDialog.openError(Display.getCurrent().getActiveShell(), "Marker Detection Errors", Joiner.on("\n").join(errors)); } StringBuilder message = new StringBuilder(); message.append("VP Count Total: "); message.append(vps.size()); for (String featureId : identifiedFeatues.elementSet()) { message.append("\n"); message.append(identifiedFeatues.count(featureId)); message.append(" x "); message.append(featureId); } MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Info", message.toString()); }
From source file:edu.uci.ics.sourcerer.tools.java.metrics.db.NumberOfClassChildrenCalculator.java
@Override public void calculate(QueryExecutor exec, Integer projectID, ProjectMetricModel metrics, TypeModel model) { TaskProgressLogger task = TaskProgressLogger.get(); Pattern anon = Pattern.compile(".*\\$\\d+$"); task.start("Computing NumberOfClassChildren"); Multiset<ModeledDeclaredType> parents = HashMultiset.create(); Multiset<ModeledDeclaredType> directParents = HashMultiset.create(); task.start("Processing classes", "classes processed"); for (ModeledEntity entity : model.getEntities()) { if (projectID.equals(entity.getProjectID()) && entity.getType() == Entity.CLASS && !anon.matcher(entity.getFqn()).matches()) { ModeledDeclaredType dec = (ModeledDeclaredType) entity; ModeledEntity sup = dec.getSuperclass(); boolean first = true; while (sup != null) { if (sup.getType() == Entity.PARAMETERIZED_TYPE) { sup = ((ModeledParametrizedType) sup).getBaseType(); } else if (projectID.equals(sup.getProjectID())) { if (sup instanceof ModeledDeclaredType) { ModeledDeclaredType ssup = (ModeledDeclaredType) sup; if (first) { directParents.add(ssup); first = false; }/*from www .ja v a 2 s . co m*/ parents.add(ssup); sup = ssup.getSuperclass(); } else { logger.severe("Declared type expected: " + sup); sup = null; } } else { sup = null; } } task.progress(); } } task.finish(); Averager<Double> avgNoc = Averager.create(); Averager<Double> avgDnoc = Averager.create(); for (ModeledEntity entity : model.getEntities()) { if (projectID.equals(entity.getProjectID()) && entity.getType() == Entity.CLASS && !anon.matcher(entity.getFqn()).matches()) { ModeledDeclaredType dec = (ModeledDeclaredType) entity; Double value = metrics.getEntityValue(dec.getEntityID(), Metric.NUMBER_OF_CLASS_CHILDREN); if (value == null) { value = (double) parents.count(dec); metrics.setEntityValue(dec.getEntityID(), dec.getFileID(), Metric.NUMBER_OF_CLASS_CHILDREN, value); exec.insert(EntityMetricsTable.createInsert(projectID, dec.getFileID(), dec.getEntityID(), Metric.NUMBER_OF_CLASS_CHILDREN, value)); } avgNoc.addValue(value); value = metrics.getEntityValue(dec.getEntityID(), Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN); if (value == null) { value = (double) directParents.count(dec); metrics.setEntityValue(dec.getEntityID(), dec.getFileID(), Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN, value); exec.insert(EntityMetricsTable.createInsert(projectID, dec.getFileID(), dec.getEntityID(), Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN, value)); } avgDnoc.addValue(value); } } if (metrics.missingValue(Metric.NUMBER_OF_CLASS_CHILDREN)) { metrics.setValue(Metric.NUMBER_OF_CLASS_CHILDREN, avgNoc); exec.insert(ProjectMetricsTable.createInsert(projectID, Metric.NUMBER_OF_CLASS_CHILDREN, avgNoc)); } if (metrics.missingValue(Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN)) { metrics.setValue(Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN, avgDnoc); exec.insert( ProjectMetricsTable.createInsert(projectID, Metric.NUMBER_OF_DIRECT_CLASS_CHILDREN, avgDnoc)); } task.finish(); }
From source file:com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle.java
/** * Change the route this vehicle is following. The route must adhere to the * following requirements://from ww w .j av a 2 s. c o m * <ul> * <li>Parcels that have not yet been picked up can at maximum occur twice in * the route.</li> * <li>Parcels that have been picked up can occur at maximum once in the * route.</li> * <li>Parcels that are delivered may not occur in the route.</li> * </ul> * These requirements are <b>not</b> checked defensively! It is the callers * responsibility to make sure this is the case. Note that the underlying * models normally <i>should</i> throw exceptions whenever a vehicle attempts * to revisit an already delivered parcel. * <p> * In some cases the models do not allow this vehicle to change its route * immediately. If this is the case the route is changed the next time this * vehicle enters its {@link #waitState}. If * {@link #isDelayedRouteChangingAllowed()} is set to <code>false</code> any * attempts to do this will result in a runtime exception, in this case the * caller must ensure that a route can be changed immediately or call this * method at a later time. The situations when the route is changed * immediately are: * <ul> * <li>If the vehicle is waiting.</li> * <li>If diversion is allowed and the vehicle is not currently servicing. * </li> * <li>If the current route is empty.</li> * <li>If the first destination in the new route equals the first destination * of the current route.</li> * </ul> * @param r The route to set. The elements are copied from the * {@link Iterable} using its iteration order. */ public void setRoute(Iterable<? extends Parcel> r) { final Iterable<Parcel> adjustedRoute = routeAdjuster.adjust(r, this); LOGGER.trace("{} setRoute {}", this, adjustedRoute); // note: the following checks can not detect if a parcel has been set to // multiple vehicles at the same time final Multiset<Parcel> routeSet = LinkedHashMultiset.create(adjustedRoute); for (final Parcel dp : routeSet.elementSet()) { final ParcelState state = getPDPModel().getParcelState(dp); checkArgument(!state.isDelivered(), "A parcel that is already delivered can not be part of a route. " + "Parcel %s in route %s.", dp, adjustedRoute); if (state.isTransitionState()) { if (state == ParcelState.PICKING_UP) { checkArgument(getPDPModel().getVehicleState(this) == VehicleState.PICKING_UP, "When a parcel in the route is in PICKING UP state the vehicle " + "must also be in that state, route: %s.", adjustedRoute, getPDPModel().getVehicleState(this)); } else { checkArgument(getPDPModel().getVehicleState(this) == VehicleState.DELIVERING, "When a parcel in the route is in DELIVERING state the vehicle" + " must also be in that state."); } checkArgument(getPDPModel().getVehicleActionInfo(this).getParcel() == dp, "A parcel in the route that is being serviced should be serviced by" + " this truck. This truck is servicing %s.", getPDPModel().getVehicleActionInfo(this).getParcel()); } final int frequency = routeSet.count(dp); if (state.isPickedUp()) { checkArgument(getPDPModel().getContents(this).contains(dp), "A parcel that is in cargo state must be in cargo of this " + "vehicle."); checkArgument(frequency <= 1, "A parcel that is in cargo may not occur more than once in a route," + " found %s instance(s) of %s.", frequency, dp, state); } else { checkArgument(frequency <= 2, "A parcel that is available may not occur more than twice in a " + "route, found %s instance(s) of %s (with state %s). Route: %s.", frequency, dp, state, adjustedRoute); } } final boolean firstEqualsFirst = firstEqualsFirstInRoute(adjustedRoute); final boolean divertable = isDiversionAllowed && !stateMachine.stateIs(serviceState); if (stateMachine.stateIs(waitState) || route.isEmpty() || divertable || firstEqualsFirst) { route = newLinkedList(adjustedRoute); newRoute = Optional.absent(); } else { checkArgument(allowDelayedRouteChanges, "Diversion is not allowed in current state and delayed route changes " + "are also not allowed, rejected route: %s.", adjustedRoute); newRoute = Optional.of(newLinkedList(adjustedRoute)); } }