List of usage examples for java.util TreeMap firstEntry
public Map.Entry<K, V> firstEntry()
From source file:com.ape.camera2raw.Camera2RawFragment.java
/** * Retrieve the next {@link Image} from a reference counted {@link ImageReader}, retaining * that {@link ImageReader} until that {@link Image} is no longer in use, and set this * {@link Image} as the result for the next request in the queue of pending requests. If * all necessary information is available, begin saving the image to a file in a background * thread./*from www . jav a 2s. c o m*/ * * @param pendingQueue the currently active requests. * @param reader a reference counted wrapper containing an {@link ImageReader} from which * to acquire an image. */ private void dequeueAndSaveImage(TreeMap<Integer, ImageSaver.ImageSaverBuilder> pendingQueue, RefCountedAutoCloseable<ImageReader> reader) { synchronized (mCameraStateLock) { Map.Entry<Integer, ImageSaver.ImageSaverBuilder> entry = pendingQueue.firstEntry(); ImageSaver.ImageSaverBuilder builder = entry.getValue(); // Increment reference count to prevent ImageReader from being closed while we // are saving its Images in a background thread (otherwise their resources may // be freed while we are writing to a file). if (reader == null || reader.getAndRetain() == null) { Log.e(TAG, "Paused the activity before we could save the image," + " ImageReader already closed."); pendingQueue.remove(entry.getKey()); return; } Image image; try { image = reader.get().acquireNextImage(); } catch (IllegalStateException e) { Log.e(TAG, "Too many images queued for saving, dropping image for request: " + entry.getKey()); pendingQueue.remove(entry.getKey()); return; } builder.setRefCountedReader(reader).setImage(image); handleCompletionLocked(entry.getKey(), builder, pendingQueue); } }
From source file:org.finra.herd.dao.helper.EmrPricingHelper.java
/** * Finds all the clusters that are within the range of lowest core instance price. * <p>//from w w w. ja va2s .c o m * For example, if the core prices are 0.30, 0.32, 0.34, 0.36, and the threshold value is 0.1(10%), then the lowest core price range should be [0.30, 0.33]. * The upper bound is derived by calculating 0.30*(1 + 0.1) = 0.33 * * @param emrClusterPrices the list of clusters to select from * @param lowestCoreInstancePriceThresholdPercentage the threshold value that defines the range of lowest core instance price * * @return the list of clusters that fall in lowest core instance price range */ List<EmrClusterPriceDto> getEmrClusterPricesWithinLowestCoreInstancePriceThreshold( final List<EmrClusterPriceDto> emrClusterPrices, final BigDecimal lowestCoreInstancePriceThresholdPercentage) { // Builds a tree map that has the core instance price as the key, and the list of pricing with the same core instance price as the value. The tree map // is automatically sorted, so it is easy to find the lowest core instance price range. TreeMap<BigDecimal, List<EmrClusterPriceDto>> emrClusterPriceMapKeyedByCoreInstancePrice = new TreeMap<>(); for (final EmrClusterPriceDto emrClusterPriceDto : emrClusterPrices) { final BigDecimal coreInstancePrice = getEmrClusterCoreInstancePrice(emrClusterPriceDto); if (emrClusterPriceMapKeyedByCoreInstancePrice.containsKey(coreInstancePrice)) { emrClusterPriceMapKeyedByCoreInstancePrice.get(coreInstancePrice).add(emrClusterPriceDto); } else { List<EmrClusterPriceDto> emrClusterPriceList = new ArrayList<>(); emrClusterPriceList.add(emrClusterPriceDto); emrClusterPriceMapKeyedByCoreInstancePrice.put(coreInstancePrice, emrClusterPriceList); } } // Log all the information in the tree map LOGGER.info("All available EMR clusters keyed by core instance price: availableEmrClusters={}", jsonHelper.objectToJson(emrClusterPriceMapKeyedByCoreInstancePrice)); // Finds the list of pricing in the range of the lowest core instance price List<EmrClusterPriceDto> lowestCoreInstancePriceEmrClusters = new ArrayList<>(); if (!emrClusterPriceMapKeyedByCoreInstancePrice.isEmpty()) { // calculate the lowest core instance price range final BigDecimal lowestCoreInstancePriceLowerBound = emrClusterPriceMapKeyedByCoreInstancePrice .firstEntry().getKey(); final BigDecimal lowestCoreInstancePriceUpperBound = lowestCoreInstancePriceLowerBound .multiply(BigDecimal.ONE.add(lowestCoreInstancePriceThresholdPercentage)); LOGGER.info("emrClusterLowestCoreInstancePriceRange={}", jsonHelper.objectToJson( Arrays.asList(lowestCoreInstancePriceLowerBound, lowestCoreInstancePriceUpperBound))); for (final Map.Entry<BigDecimal, List<EmrClusterPriceDto>> entry : emrClusterPriceMapKeyedByCoreInstancePrice .entrySet()) { final BigDecimal coreInstancePrice = entry.getKey(); // Fall into the lowest price range? add it to the list. // There is no need to check the lower bound here, since the tree map is sorted, and lower bound is the lowest core price in the tree map. if (coreInstancePrice.compareTo(lowestCoreInstancePriceUpperBound) <= 0) { lowestCoreInstancePriceEmrClusters.addAll(entry.getValue()); } else { // since the tree map is sorted in ascending order, we do not need to check the rest of entries in the map break; } } } return lowestCoreInstancePriceEmrClusters; }
From source file:statistic.ca.gui.JCAStatisticPanel.java
private void showDiagramm(String diagrammName) { if (diagrammName.equals("Grundinformationen")) { String[] columnNames = { "Bezeichnung", "Wert" }; EvacuationCellularAutomaton tmpCA; int nrOfInd = 0; double evacSec = 0.0; double evacCAStep = 0; double notEvac = 0; double evac = 0; double notEvacNoExit = 0; double notEvacNoTime = 0; int bestEvacIndex = 0; int aveEvacIndex = 0; int worseEvacIndex = 0; TreeMap<Double, Integer> findMedian = new TreeMap<>(); for (int i = 0; i < selectedBatchResultEntry.getCa().length; i++) { tmpCA = selectedBatchResultEntry.getCa()[i]; nrOfInd += tmpCA.getInitialIndividualCount(); evacSec += tmpCA.getSecondsPerStep() * tmpCA.getTimeStep(); evacCAStep += tmpCA.getTimeStep(); evac += tmpCA.getInitialIndividualCount() - tmpCA.deadIndividualsCount(); notEvac += tmpCA.deadIndividualsCount(); notEvacNoExit += tmpCA.getDeadIndividualCount(DeathCause.ExitUnreachable);// getNrOfExitUnreachableDeadIndividuals(); notEvacNoTime += tmpCA.getDeadIndividualCount(DeathCause.NotEnoughTime);// getNrOfNotEnoughTimeDeadIndividuals(); findMedian.put(tmpCA.getTimeStep() * tmpCA.getSecondsPerStep(), i); }/*from w w w. j ava 2 s. c o m*/ bestEvacIndex = findMedian.firstEntry().getValue(); for (int j = 0; j < findMedian.size() / 2; j++) findMedian.remove(findMedian.firstKey()); aveEvacIndex = findMedian.get(findMedian.firstKey()); worseEvacIndex = findMedian.get(findMedian.lastKey()); Object[][] data = { { "Informationen fr Modell", selectedBatchResultEntry.getName() }, { "Evakuierungszeit in Sekunden", evacSec / selectedBatchResultEntry.getCa().length }, { "Evakuierungszeit in ZA-Schritten", evacCAStep / selectedBatchResultEntry.getCa().length }, { "Anzahl Individuen", (double) nrOfInd / selectedBatchResultEntry.getCa().length }, { "evakuiert", evac / selectedBatchResultEntry.getCa().length }, { "nicht evakuiert", notEvac / selectedBatchResultEntry.getCa().length }, { "nicht evakuiert weil kein Ausgang erreichbar", notEvacNoExit / selectedBatchResultEntry.getCa().length }, { "nicht evakuiert weil die Zeit nicht gereicht hat", notEvacNoTime / selectedBatchResultEntry.getCa().length }, { "beste Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (bestEvacIndex + 1) + " - " + (selectedBatchResultEntry.getCa()[bestEvacIndex].getTimeStep() / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond()) + ")") }, { "durchschnit. Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (aveEvacIndex + 1) + " - " + (selectedBatchResultEntry.getCa()[aveEvacIndex].getTimeStep() / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond()) + ")") }, { "schlechteste Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (worseEvacIndex + 1) + " - " + (selectedBatchResultEntry.getCa()[worseEvacIndex].getTimeStep() / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond()) + ")") } }; basicInformationTable = new JTable(data, columnNames); basicInformationScrollPane = new JScrollPane(basicInformationTable); diagrams.addTable(diagrammName, basicInformationScrollPane, west); } if ((noIndividualsInAtLeastOneAssignmentIndex) && !(diagrammName.equals("Grundinformationen"))) { chartData = new ChartData("bar", "NO INDIVIDUALS in at least one of the choosed dataset(s)", "", new ArrayList<>(), new ArrayList<>()); evakuierungsdauer = ChartFactory.createBarChart( "NO INDIVIDUALS in at least one of the choosed dataset(s)", "", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart("NO INDIVIDUALS in at least one of the choosed dataset(s)", evakuierungsdauer, west); } else { if (diagrammName.equals("Ausgangsverteilung")) { chartData = new ChartData("pie", diagrammName + ":" + selectedBatchResultEntry.getName() + "-" + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(), "Ausgnge", categoryDatasetValues, categoryDatasetAssignments); ausgangsverteilung = ChartFactory.createPieChart( diagrammName + ":" + selectedBatchResultEntry.getName() + "-" + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(), ChartData.getPieDataSet(), false, true, false); diagrams.addChart(diagrammName, ausgangsverteilung, west); } if (diagrammName.equals("Ankunftskurve")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); ankunftskurve = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Individuen", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, ankunftskurve, west); } if (diagrammName.equals("Evakuierungsdauer")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); evakuierungsdauer = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, evakuierungsdauer, west); } if (diagrammName.equals("evakuierte Individuen in Prozent")) { chartData = new ChartData("pie", diagrammName + ":" + selectedBatchResultEntry.getName() + "-" + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(), "Individuen", categoryDatasetValues, categoryDatasetAssignments); evakuierteIndividueninProzent = ChartFactory.createPieChart( diagrammName + ":" + selectedBatchResultEntry.getName() + "-" + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(), ChartData.getPieDataSet(), false, true, false); diagrams.addChart(diagrammName, evakuierteIndividueninProzent, west); } if (diagrammName.equals("maximale Blockadezeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); maxblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, maxblockadezeit, west); } if (diagrammName.equals("durchschnittliche Blockadezeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); aveblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, aveblockadezeit, west); } if (diagrammName.equals("minimale Blockadezeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); minblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, minblockadezeit, west); } if (diagrammName.equals("zurckgelegte Distanz")) { chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues, categoryDatasetAssignments); zurueckgelegteDistanz = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, zurueckgelegteDistanz, west); } if (diagrammName.equals("minimale Distanz zum initialen Ausgang")) { chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues, categoryDatasetAssignments); minimaleDistanzzuminitialenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, minimaleDistanzzuminitialenAusgang, west); } if (diagrammName.equals("minimale Distanz zum nchsten Ausgang")) { chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues, categoryDatasetAssignments); minimaleDistanzzumnaechstenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, minimaleDistanzzumnaechstenAusgang, west); } if (diagrammName.equals("maximale Zeit bis Safe")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); maxZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, maxZeitBisSafe, west); } if (diagrammName.equals("durchschnittliche Zeit bis Safe")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); aveZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, aveZeitBisSafe, west); } if (diagrammName.equals("minimale Zeit bis Safe")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); minZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, minZeitBisSafe, west); } if (diagrammName.equals("Distanz ber Zeit")) { chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues, categoryDatasetAssignments); distanzueberZeit = ChartFactory.createXYLineChart(diagrammName, "Zeit [s]", chartData.getYAxisLabel(), (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, distanzueberZeit, west); } if (diagrammName.equals("maximale Geschwindigkeit ber Zeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); maximaleGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, maximaleGeschwindigkeitueberZeit, west); } if (diagrammName.equals("durschnittliche Geschwindigkeit ber Zeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); durschnittlicheGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, durschnittlicheGeschwindigkeitueberZeit, west); } if (diagrammName.equals("maximale Geschwindigkeit")) { chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues, categoryDatasetAssignments); maximaleGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, maximaleGeschwindigkeit, west); } if (diagrammName.equals("durchschnittliche Geschwindigkeit")) { chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues, categoryDatasetAssignments); durchschnittlicheGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false); diagrams.addChart(diagrammName, durchschnittlicheGeschwindigkeit, west); } if (diagrammName.equals("Panik ber Zeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); panik = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Panik", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, panik, west); } if (diagrammName.equals("Erschpfung ber Zeit")) { chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues, categoryDatasetAssignments); erschoepfung = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Erschpfung", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false); diagrams.addChart(diagrammName, erschoepfung, west); } } //end else categoryDatasetValues = new ArrayList<>(); categoryDatasetAssignments = new ArrayList<>(); //dataset = new XYSeries(""); datasetCollection = new XYSeriesCollection(); diagrams.validate(); }
From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java
/** * Read the settings from disk./* w w w .j a va2 s . c o m*/ */ public void load() { try { FileExportSettings settings = FileExportSettings.load(); if (settings != null) { Path path = settings.getFilesRootDirectory(); if (path != null) { tbRootDirectory.setText(path.toString()); } path = settings.getReportsRootDirectory(); if (path != null) { tbReportDirectory.setText(path.toString()); } TreeMap<String, FileExportRuleSet> treeMap = settings.getRuleSets(); if (treeMap != null && !treeMap.isEmpty()) { exportRuleSet = treeMap.firstEntry().getValue(); } boolean answer = settings.getFileExportEnabledState(); setEnabledState(answer); cbEnableFileExport.setSelected(answer); } return; } catch (FileExportSettings.PersistenceException ex) { logger.log(Level.INFO, "Unable to load rule settings: {0}", ex.getMessage()); //NON-NLS } setEnabledState(false); cbEnableFileExport.setSelected(false); }
From source file:edu.dfci.cccb.mev.hcl.domain.simple.SimpleTwoDimensionalHclBuilder.java
private Node cluster(final Dataset dataset, Dimension dimension, Metric metric, Linkage linkage) throws DatasetException { final Type dimensionType = dimension.type(); final RealMatrix original = toRealMatrix(dataset); final int size = dimensionType == ROW ? original.getRowDimension() : original.getColumnDimension(); final int other = dimensionType == COLUMN ? original.getRowDimension() : original.getColumnDimension(); Iterator<Integer> enumerator = new Iterator<Integer>() { private int counter = -1; @Override// www. jav a 2s. c o m public boolean hasNext() { return true; } @Override public Integer next() { counter--; if (counter > 0) counter = -1; return counter; } @Override public void remove() { throw new UnsupportedOperationException(); } }; final double[][] distances = new double[size][size]; log.debug("Populating node hash"); final Map<Integer, Node> genehash = new HashMap<Integer, Node>() { private static final long serialVersionUID = 1L; { for (int index = size; --index >= 0; put(index, nodeBuilder().leaf(dataset.dimension(dimensionType).keys().get(index)))) ; } }; TreeMap<Double, int[]> sorted = new TreeMap<>(); log.debug("Populating distance matrix"); for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { double distance = metric.distance(new AbstractList<Double>() { private int i; @Override public Double get(int index) { return dimensionType == ROW ? original.getEntry(i, index) : original.getEntry(index, i); } @Override public int size() { return other; } private List<Double> initializeProjection(int i) { this.i = i; return this; } }.initializeProjection(i), new AbstractList<Double>() { private int j; @Override public Double get(int index) { return dimensionType == ROW ? original.getEntry(j, index) : original.getEntry(index, j); } @Override public int size() { return other; } private List<Double> initializeProjection(int j) { this.j = j; return this; } }.initializeProjection(j)); distances[i][j] = distance; distances[j][i] = distance; int[] genePair = { i, j }; // Enter the distance calculated and the genes measured into a // treemap. Will be automatically sorted. sorted.put(distance, genePair); } } log.debug("Aggregating"); while (true) { // Get the first key of the TreeMap. Will be the shortest distance de // facto. final double minkey = (Double) sorted.firstKey(); int[] minValues = (int[]) sorted.firstEntry().getValue(); final int value1 = minValues[0], value2 = minValues[1]; // find Node cluster = nodeBuilder().branch(minkey, genehash.get(value1), genehash.get(value2)); int id = enumerator.next(); genehash.put(id, cluster); genehash.remove(value1); genehash.remove(value2); if (genehash.size() <= 1) break; // Iterate over all the current clusters to remeasure distance with the // previously clustered group. for (Entry<Integer, Node> e : genehash.entrySet()) { Node c = e.getValue(); // Skip measuring the new cluster with itself. if (c == cluster) continue; List<Double> aggregation = new ArrayList<>(); // Get genes from each cluster. Distance is measured from each element // to every element. for (int current : traverse(dimension.keys(), c)) for (int created : traverse(dimension.keys(), cluster)) aggregation.add(distances[current][created]); int[] valuePair = { e.getKey(), id }; sorted.put(linkage.aggregate(aggregation), valuePair); } // Get the shortest distance. // Check to make sure shortest distance does not include a gene pair // that // has already had its elements clustered. boolean minimized = false; while (!minimized) { double mk = sorted.firstKey(); minValues = sorted.firstEntry().getValue(); // If the gene pair is not present in the current gene set, remove // this distance. if (!genehash.containsKey(minValues[0]) || !genehash.containsKey(minValues[1])) sorted.remove(mk); else minimized = true; } } Node result = genehash.entrySet().iterator().next().getValue(); log.debug("Clustered " + result); return result; }
From source file:com.evolveum.midpoint.provisioning.impl.ResourceObjectConverter.java
private List<Collection<Operation>> sortOperationsIntoWaves(Collection<Operation> operations, RefinedObjectClassDefinition objectClassDefinition) { TreeMap<Integer, Collection<Operation>> waves = new TreeMap<>(); // operations indexed by priority List<Operation> others = new ArrayList<>(); // operations executed at the end (either non-priority ones or non-attribute modifications) for (Operation operation : operations) { RefinedAttributeDefinition rad = getRefinedAttributeDefinitionIfApplicable(operation, objectClassDefinition);/*from w ww . java2 s .c o m*/ if (rad != null && rad.getModificationPriority() != null) { putIntoWaves(waves, rad.getModificationPriority(), operation); continue; } others.add(operation); } // computing the return value List<Collection<Operation>> retval = new ArrayList<>(waves.size() + 1); Map.Entry<Integer, Collection<Operation>> entry = waves.firstEntry(); while (entry != null) { retval.add(entry.getValue()); entry = waves.higherEntry(entry.getKey()); } retval.add(others); return retval; }
From source file:org.xwiki.contrib.mailarchive.timeline.internal.TimeLineGenerator.java
/** * {@inheritDoc}/*from www. jav a2s .c o m*/ * * @see org.xwiki.contrib.mailarchive.timeline.ITimeLineGenerator#compute() */ @Override public String compute(int maxItems) { try { config.reloadConfiguration(); } catch (MailArchiveException e) { logger.error("Could not load mail archive configuration", e); return null; } Map<String, IMailingList> mailingLists = config.getMailingLists(); Map<String, IType> types = config.getMailTypes(); try { this.userStatsUrl = xwiki.getDocument(docResolver.resolve("MailArchive.ViewUserMessages"), context) .getURL("view", context); } catch (XWikiException e1) { logger.warn("Could not retrieve user stats url {}", ExceptionUtils.getRootCauseMessage(e1)); } TreeMap<Long, TimeLineEvent> sortedEvents = new TreeMap<Long, TimeLineEvent>(); // Set loading user in context (for rights) String loadingUser = config.getLoadingUser(); context.setUserReference(docResolver.resolve(loadingUser)); try { // Search topics String xwql = "select doc.fullName, topic.author, topic.subject, topic.topicid, topic.startdate, topic.lastupdatedate from Document doc, doc.object(" + XWikiPersistence.CLASS_TOPICS + ") as topic order by topic.lastupdatedate desc"; List<Object[]> result = queryManager.createQuery(xwql, Query.XWQL).setLimit(maxItems).execute(); for (Object[] item : result) { XWikiDocument doc = null; try { String docurl = (String) item[0]; String author = (String) item[1]; String subject = (String) item[2]; String topicId = (String) item[3]; Date date = (Date) item[4]; Date end = (Date) item[5]; String action = ""; // Retrieve associated emails TreeMap<Long, TopicEventBubble> emails = getTopicMails(topicId, subject); if (emails == null || emails.isEmpty()) { // Invalid topic, not emails attached, do not show it logger.warn("Invalid topic, no emails attached " + doc); } else { if (date != null && end != null && date.equals(end)) { // Add 10 min just to see the tape end.setTime(end.getTime() + 600000); } doc = xwiki.getDocument(docResolver.resolve(docurl), context); final List<String> tagsList = doc.getTagsList(context); List<String> topicTypes = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "type"); // Email type icon List<String> icons = new ArrayList<String>(); for (String topicType : topicTypes) { IType type = types.get(topicType); if (type != null && !StringUtils.isEmpty(type.getIcon())) { icons.add(xwiki.getSkinFile("icons/silk/" + type.getIcon() + ".png", context)); // http://localhost:8080/xwiki/skins/colibri/icons/silk/bell // http://localhost:8080/xwiki/resources/icons/silk/bell.png } } // Author and avatar final IMAUser wikiUser = mailUtils.parseUser(author, config.isMatchLdap()); final String authorAvatar = getAuthorAvatar(wikiUser.getWikiProfile()); final TimeLineEvent timelineEvent = new TimeLineEvent(); TimeLineEvent additionalEvent = null; timelineEvent.beginDate = date; timelineEvent.title = subject; timelineEvent.icons = icons; timelineEvent.lists = doc.getListValue(XWikiPersistence.CLASS_TOPICS, "list"); timelineEvent.author = wikiUser.getDisplayName(); timelineEvent.authorAvatar = authorAvatar; timelineEvent.extract = getExtract(topicId); if (emails.size() == 1) { logger.debug("Adding instant event for email '" + subject + "'"); // Unique email, we show a punctual email event timelineEvent.url = emails.firstEntry().getValue().link; timelineEvent.action = "New Email "; } else { // For email with specific type icon, and a duration, both a band and a point should be added (so 2 events) // because no icon is displayed for duration events. if (CollectionUtils.isNotEmpty(icons)) { logger.debug( "Adding additional instant event to display type icon for first email in topic"); additionalEvent = new TimeLineEvent(timelineEvent); additionalEvent.url = emails.firstEntry().getValue().link; additionalEvent.action = "New Email "; } // Email thread, we show a topic event (a range) logger.debug("Adding duration event for topic '" + subject + "'"); timelineEvent.endDate = end; timelineEvent.url = doc.getURL("view", context); timelineEvent.action = "New Topic "; timelineEvent.messages = emails; } // Add the generated Event to the list if (sortedEvents.containsKey(date.getTime())) { // Avoid having more than 1 event at exactly the same time, because some timeline don't like it date.setTime(date.getTime() + 1); } sortedEvents.put(date.getTime(), timelineEvent); if (additionalEvent != null) { sortedEvents.put(date.getTime() + 1, additionalEvent); } } } catch (Throwable t) { logger.warn("Exception for " + doc, t); } } } catch (Throwable e) { logger.warn("could not compute timeline data", e); } return printEvents(sortedEvents); }
From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java
@Override public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserContext userContext = toUserContext(user); TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues); try {/*from www.ja v a2 s . com*/ AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount( new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId())) .getParentAccount(); BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount(); BigDecimal membersAmount = BigDecimal.ZERO; for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) { LoanBO individual = loanDao.findById(entry.getKey()); Double chargeAmount = Double.valueOf(entry.getValue()); if (chargeAmount.equals(0.0)) { continue; } membersAmount = membersAmount.add(individual.getLoanAmount().getAmount()); individual.updateDetails(userContext); if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount)); } else { individual.applyCharge(chargeId, chargeAmount); } } boolean isRateCharge = false; if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES)) && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { if (isPenaltyType) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); if (penalty instanceof RatePenaltyBO) { isRateCharge = true; } } else { FeeBO fee = feeDao.findById(chargeId); if (fee.getFeeType().equals(RateAmountFlag.RATE)) { isRateCharge = true; } } } Double chargeAmount = null; if (!isRateCharge) { chargeAmount = sumCharge(idsAndValues); } else { chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue()); BigDecimal chargeAmountBig = new BigDecimal(chargeAmount); membersAmount = membersAmount.multiply(chargeAmountBig); int scale = Money.getInternalPrecision(); chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN); chargeAmount = chargeAmountBig.doubleValue(); } parentAccount.updateDetails(userContext); CustomerLevel customerLevel = null; if (parentAccount.isCustomerAccount()) { customerLevel = parentAccount.getCustomer().getLevel(); } if (parentAccount.getPersonnel() != null) { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId()); } else { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), userContext.getId()); } this.transactionHelper.startTransaction(); if (isPenaltyType && parentAccount instanceof LoanBO) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); ((LoanBO) parentAccount) .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount)); } else { parentAccount.applyCharge(chargeId, chargeAmount); } this.transactionHelper.commitTransaction(); } catch (ServiceException e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (ApplicationException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getKey(), e); } }
From source file:cx.ring.service.LocalService.java
public void updateTextNotifications() { Log.d(TAG, "updateTextNotifications()"); for (Conversation c : conversations.values()) { TreeMap<Long, TextMessage> texts = c.getUnreadTextMessages(); if (texts.isEmpty() || texts.lastEntry().getValue().isNotified()) { continue; } else//from w w w.java 2 s . c o m notificationManager.cancel(c.notificationId); CallContact contact = c.getContact(); if (c.notificationBuilder == null) { c.notificationBuilder = new NotificationCompat.Builder(getApplicationContext()); c.notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE) .setPriority(NotificationCompat.PRIORITY_HIGH).setDefaults(NotificationCompat.DEFAULT_ALL) .setSmallIcon(R.drawable.ic_launcher).setContentTitle(contact.getDisplayName()); } NotificationCompat.Builder noti = c.notificationBuilder; Intent c_intent = new Intent(Intent.ACTION_VIEW).setClass(this, ConversationActivity.class) .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0))); Intent d_intent = new Intent(ACTION_CONV_READ).setClass(this, LocalService.class) .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0))); noti.setContentIntent(PendingIntent.getActivity(this, new Random().nextInt(), c_intent, 0)) .setDeleteIntent(PendingIntent.getService(this, new Random().nextInt(), d_intent, 0)); if (contact.getPhoto() != null) { Resources res = getResources(); int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height); int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width); noti.setLargeIcon(Bitmap.createScaledBitmap(contact.getPhoto(), width, height, false)); } if (texts.size() == 1) { TextMessage txt = texts.firstEntry().getValue(); txt.setNotified(true); noti.setContentText(txt.getMessage()); noti.setStyle(null); noti.setWhen(txt.getTimestamp()); } else { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (TextMessage s : texts.values()) { inboxStyle.addLine(Html.fromHtml("<b>" + DateUtils.formatDateTime(this, s.getTimestamp(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL) + "</b> " + s.getMessage())); s.setNotified(true); } noti.setContentText(texts.lastEntry().getValue().getMessage()); noti.setStyle(inboxStyle); noti.setWhen(texts.lastEntry().getValue().getTimestamp()); } notificationManager.notify(c.notificationId, noti.build()); } }
From source file:org.apache.accumulo.tserver.TabletServer.java
private TreeMap<KeyExtent, TabletData> splitTablet(Tablet tablet, byte[] splitPoint) throws IOException { long t1 = System.currentTimeMillis(); TreeMap<KeyExtent, TabletData> tabletInfo = tablet.split(splitPoint); if (tabletInfo == null) { return null; }/*www.j a va 2s. c o m*/ log.info("Starting split: " + tablet.getExtent()); statsKeeper.incrementStatusSplit(); long start = System.currentTimeMillis(); Tablet[] newTablets = new Tablet[2]; Entry<KeyExtent, TabletData> first = tabletInfo.firstEntry(); TabletResourceManager newTrm0 = resourceManager.createTabletResourceManager(first.getKey(), getTableConfiguration(first.getKey())); newTablets[0] = new Tablet(TabletServer.this, first.getKey(), newTrm0, first.getValue()); Entry<KeyExtent, TabletData> last = tabletInfo.lastEntry(); TabletResourceManager newTrm1 = resourceManager.createTabletResourceManager(last.getKey(), getTableConfiguration(last.getKey())); newTablets[1] = new Tablet(TabletServer.this, last.getKey(), newTrm1, last.getValue()); // roll tablet stats over into tablet server's statsKeeper object as // historical data statsKeeper.saveMajorMinorTimes(tablet.getTabletStats()); // lose the reference to the old tablet and open two new ones synchronized (onlineTablets) { onlineTablets.remove(tablet.getExtent()); onlineTablets.put(newTablets[0].getExtent(), newTablets[0]); onlineTablets.put(newTablets[1].getExtent(), newTablets[1]); } // tell the master enqueueMasterMessage(new SplitReportMessage(tablet.getExtent(), newTablets[0].getExtent(), new Text("/" + newTablets[0].getLocation().getName()), newTablets[1].getExtent(), new Text("/" + newTablets[1].getLocation().getName()))); statsKeeper.updateTime(Operation.SPLIT, start, 0, false); long t2 = System.currentTimeMillis(); log.info("Tablet split: " + tablet.getExtent() + " size0 " + newTablets[0].estimateTabletSize() + " size1 " + newTablets[1].estimateTabletSize() + " time " + (t2 - t1) + "ms"); return tabletInfo; }