List of usage examples for java.util SortedMap get
V get(Object key);
From source file:org.jasig.schedassist.portlet.VisibleScheduleTag.java
/** * Render a single week./* w w w .ja v a 2s. c o m*/ * * @param writer * @param weekNumber * @param dailySchedules * @param scheduleBlockMap * @param renderRequest * @param renderResponse * @throws IOException */ protected void renderWeek(final JspWriter writer, final int weekNumber, final SortedMap<Date, List<AvailableBlock>> dailySchedules, final SortedMap<AvailableBlock, AvailableStatus> scheduleBlockMap, final RenderRequest renderRequest, final RenderResponse renderResponse) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("begin renderWeek for " + weekNumber); } final boolean hasBlocks = doesWeekHaveBlocks(dailySchedules); if (hasBlocks) { final SimpleDateFormat headFormat = new SimpleDateFormat("EEE M/d"); writer.write("<div class=\"weekcontainer\" id=\"week" + weekNumber + "\">"); for (Map.Entry<Date, List<AvailableBlock>> entry : dailySchedules.entrySet()) { final Date day = entry.getKey(); final List<AvailableBlock> daySchedule = entry.getValue(); if (LOG.isDebugEnabled()) { LOG.debug("in renderWeek weeknumber: " + weekNumber + ", day: " + day); } if (daySchedule.size() > 0) { writer.write("<div class=\"weekday\">"); writer.write("<ul>"); writer.write("<li class=\"dayhead\">"); writer.write(headFormat.format(day)); writer.write("</li>"); for (AvailableBlock event : daySchedule) { AvailableStatus eventStatus = scheduleBlockMap.get(event); if (AvailableStatus.BUSY.equals(eventStatus)) { renderBusyBlock(writer, event); } else if (AvailableStatus.FREE.equals(eventStatus)) { renderFreeBlock(writer, event, renderRequest, renderResponse); } else if (AvailableStatus.ATTENDING.equals(eventStatus)) { renderAttendingBlock(writer, event, renderRequest, renderResponse); } } writer.write("</ul>"); writer.write("</div> <!-- end weekday -->"); } } writer.write("</div> <!-- end weekcontainer -->"); } else { if (LOG.isDebugEnabled()) { LOG.debug("renderWeek has no blocks for weekNumber: " + weekNumber); } } }
From source file:org.jahia.services.render.scripting.bundle.BundleScriptResolver.java
/** * Returns view scripts for the specified module bundle which match the specified path. * * @param module the module bundle to perform lookup in * @param pathPrefix the resource path prefix to match * @return a set of matching view scripts ordered by the extension (script type) */// w ww.ja va2 s . c o m private Set<ViewResourceInfo> findBundleScripts(String module, String pathPrefix) { final SortedMap<String, ViewResourceInfo> allBundleScripts = availableScripts.get(module); if (allBundleScripts == null || allBundleScripts.isEmpty()) { return Collections.emptySet(); } // get all the ViewResourceInfos which path is greater than or equal to the given prefix final SortedMap<String, ViewResourceInfo> viewInfosWithPathGTEThanPrefix = allBundleScripts .tailMap(pathPrefix); // if the tail map is empty, we won't find the path prefix in the available scripts so return an empty set if (viewInfosWithPathGTEThanPrefix.isEmpty()) { return Collections.emptySet(); } // check if the first key contains the prefix. If not, the prefix will not match any entries so return an empty set if (!viewInfosWithPathGTEThanPrefix.firstKey().startsWith(pathPrefix)) { return Collections.emptySet(); } else { SortedSet<ViewResourceInfo> sortedScripts = new TreeSet<ViewResourceInfo>(scriptExtensionComparator); for (String path : viewInfosWithPathGTEThanPrefix.keySet()) { // we should have only few values to look at if (path.startsWith(pathPrefix)) { sortedScripts.add(viewInfosWithPathGTEThanPrefix.get(path)); } else { // as soon as the path doesn't start with the given prefix anymore, we won't have a match in the remaining so return return sortedScripts; } } return sortedScripts; } }
From source file:io.fabric8.maven.plugin.mojo.internal.ImportMojo.java
private void chooseSshKeyPairs(Map<String, String> secretData, String host) throws MojoExecutionException { String homeDir = System.getProperty("user.home", "."); File sshDir = new File(homeDir, ".ssh"); SortedMap<String, String> keyPairs = new TreeMap<>(); if (sshDir.isDirectory() && sshDir.exists()) { File[] files = sshDir.listFiles(); if (files != null) { for (File file : files) { String publicName = file.getName(); if (file.isFile() && publicName.endsWith(".pub")) { String privateName = Strings.stripSuffix(publicName, ".pub"); if (new File(sshDir, privateName).isFile()) { keyPairs.put(privateName, publicName); }/* www . ja v a2 s.c o m*/ } } } } if (keyPairs.isEmpty()) { log.warn("No SSH key pairs could be found in %s to choose from!", sshDir); log.warn("You may want to clone the git repository over https:// instead to avoid ssh key pairs?"); } else { if (keyPairs.size() == 0) { String privateName = keyPairs.firstKey(); importSshKeys(secretData, sshDir, privateName, keyPairs.get(privateName)); } else { List<String> privateKeys = new ArrayList<>(keyPairs.keySet()); String privateKey = null; try { privateKey = prompter.prompt( "Which public / private key pair do you wish to use for SSH authentication with host: " + host, privateKeys); } catch (PrompterException e) { log.warn("Failed to get user input: %s", e); } if (Strings.isNotBlank(privateKey)) { String publicKey = keyPairs.get(privateKey); if (Strings.isNullOrBlank(publicKey)) { log.warn("Invalid answer: %s when available values are: %s", privateKey, privateKeys); } else { importSshKeys(secretData, sshDir, privateKey, publicKey); } } } } }
From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.StatisticsAction.java
private Spreadsheet generateSpreadSheet(final SortedMap<Object, BigDecimal> sumMap, final SortedMap<Object, BigDecimal> medianMap, final SortedMap<Object, BigDecimal> averageMap, final SortedMap<Object, BigDecimal> minsMap, final SortedMap<Object, BigDecimal> maxsMap) { final Spreadsheet spreadsheet = new Spreadsheet("Estatsticas"); spreadsheet.setHeader("Estado"); spreadsheet.setHeader("Soma"); spreadsheet.setHeader("Mediana Tempo (em dias)"); spreadsheet.setHeader("Mdia Tempo (em dias)"); spreadsheet.setHeader("Tempo Mnimo (em dias)"); spreadsheet.setHeader("Tempo Mximo (em dias)"); final SortedSet<Object> types = new TreeSet<Object>(); types.addAll(sumMap.keySet());/*www . jav a 2 s .c o m*/ types.addAll(medianMap.keySet()); types.addAll(averageMap.keySet()); BigDecimal DAYS_CONST = new BigDecimal(1000 * 3600 * 24); for (final Object type : types) { final BigDecimal sum = sumMap.get(type); final BigDecimal median = medianMap.get(type); final BigDecimal average = averageMap.get(type); final BigDecimal min = minsMap.get(type); final BigDecimal max = maxsMap.get(type); final Row row = spreadsheet.addRow(); row.setCell(((IPresentableEnum) type).getLocalizedName()); row.setCell(sum == null ? "0" : sum.toString()); row.setCell(median == null ? "" : median.divide(DAYS_CONST, 2, BigDecimal.ROUND_HALF_UP).toString()); row.setCell(average == null ? "" : average.divide(DAYS_CONST, 2, BigDecimal.ROUND_HALF_UP).toString()); row.setCell(min == null ? "" : min.divide(DAYS_CONST, 2, BigDecimal.ROUND_HALF_UP).toString()); row.setCell(max == null ? "" : max.divide(DAYS_CONST, 2, BigDecimal.ROUND_HALF_UP).toString()); } return spreadsheet; }
From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java
public void populateBudgetSummaryTotals(Budget budget) { BudgetCategoryType personnelCategoryType = getPersonnelCategoryType(); String personnelBudgetCategoryType = personnelCategoryType.getCode(); List<BudgetLineItem> budgetLineItems = getAllBudgetSummaryLineItems(budget); SortedMap<BudgetCategoryType, SortedMap<CostElement, List<BudgetLineItem>>> uniqueBudgetCategoryLineItemCostElements = getBudgetSummaryUniqueBudgetCategoryLineItemCostElements( budgetLineItems);// www . j av a 2 s .co m SortedMap<CostElement, List<BudgetLineItem>> personnelCostElementLineItems = uniqueBudgetCategoryLineItemCostElements .get(personnelCategoryType); List<Period> budgetSummaryPeriods = new ArrayList<>(); for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { String periodHeader = BUDGET_SUMMARY_PERIOD_HEADER_LABEL .concat(budgetPeriod.getBudgetPeriod().toString()); Period summaryPeriod = new Period(periodHeader); summaryPeriod.setStartDate(budgetPeriod.getStartDate()); summaryPeriod.setEndDate(budgetPeriod.getEndDate()); if (personnelCostElementLineItems != null) { LineItemGroup personnelGroup = getPersonnelBudgetSummaryPeriods(budgetPeriod, personnelCostElementLineItems, personnelBudgetCategoryType); LineItemObject calculatedPersonnelDirectCosts = new LineItemObject( BudgetSummaryConstants.CalculatedDirectCost.getKey(), BudgetSummaryConstants.CalculatedDirectCost.getLabel(), ScaleTwoDecimal.ZERO); ScaleTwoDecimal personnelDirectCost = getCalculateBudgetSummaryExpenseTotal(budgetPeriod, true, personnelBudgetCategoryType); calculatedPersonnelDirectCosts.setAmount(personnelDirectCost); personnelGroup.getLineItems().add(calculatedPersonnelDirectCosts); summaryPeriod.getLineItemGroups().add(personnelGroup); } uniqueBudgetCategoryLineItemCostElements.remove(personnelCategoryType); LineItemGroup nonPersonnelGroup = getNonPersonnelBudgetSummaryPeriods(budgetPeriod, uniqueBudgetCategoryLineItemCostElements); LineItemObject calculatedNonPersonnelDirectCosts = new LineItemObject( BudgetSummaryConstants.CalculatedDirectCost.getKey(), BudgetSummaryConstants.CalculatedDirectCost.getLabel(), ScaleTwoDecimal.ZERO); ScaleTwoDecimal nonPersonnelDirectCost = getCalculateBudgetSummaryExpenseTotal(budgetPeriod, false, personnelBudgetCategoryType); calculatedNonPersonnelDirectCosts.setAmount(nonPersonnelDirectCost); nonPersonnelGroup.getLineItems().add(calculatedNonPersonnelDirectCosts); summaryPeriod.getLineItemGroups().add(nonPersonnelGroup); LineItemGroup totalsGroup = getBudgetSummaryTotals(budgetPeriod); summaryPeriod.getLineItemGroups().add(totalsGroup); budgetSummaryPeriods.add(summaryPeriod); } budget.setBudgetSummaryDetails(budgetSummaryPeriods); }
From source file:tajo.master.GlobalPlanner.java
private Map<TupleRange, Set<URI>> rangeFetches(Schema schema, List<URI> uriList) throws UnsupportedEncodingException { SortedMap<TupleRange, Set<URI>> map = Maps.newTreeMap(); TupleRange range;//from www . ja va2 s . c om Set<URI> uris; for (URI uri : uriList) { range = TupleUtil.queryToRange(schema, uri.getQuery()); // URI.getQuery() returns a url-decoded query string. if (map.containsKey(range)) { uris = map.get(range); uris.add(uri); } else { uris = Sets.newHashSet(); uris.add(uri); map.put(range, uris); } } return map; }
From source file:org.codehaus.mojo.license.api.DefaultThirdPartyTool.java
/** * {@inheritDoc}//from w w w . j ava 2 s .c om */ public SortedProperties loadUnsafeMapping(LicenseMap licenseMap, SortedMap<String, MavenProject> artifactCache, String encoding, File missingFile) throws IOException { SortedSet<MavenProject> unsafeDependencies = getProjectsWithNoLicense(licenseMap, false); SortedProperties unsafeMappings = new SortedProperties(encoding); if (missingFile.exists()) { // there is some unsafe dependencies getLogger().info("Load missing file " + missingFile); // load the missing file unsafeMappings.load(missingFile); } // get from the missing file, all unknown dependencies List<String> unknownDependenciesId = new ArrayList<String>(); // coming from maven-license-plugin, we used the full g/a/v/c/t. Now we remove classifier and type // since GAV is good enough to qualify a license of any artifact of it... Map<String, String> migrateKeys = migrateMissingFileKeys(unsafeMappings.keySet()); for (Object o : migrateKeys.keySet()) { String id = (String) o; String migratedId = migrateKeys.get(id); MavenProject project = artifactCache.get(migratedId); if (project == null) { // now we are sure this is a unknown dependency unknownDependenciesId.add(id); } else { if (!id.equals(migratedId)) { // migrates id to migratedId getLogger().info("Migrates [" + id + "] to [" + migratedId + "] in the missing file."); Object value = unsafeMappings.get(id); unsafeMappings.remove(id); unsafeMappings.put(migratedId, value); } } } if (!unknownDependenciesId.isEmpty()) { // there is some unknown dependencies in the missing file, remove them for (String id : unknownDependenciesId) { getLogger().warn( "dependency [" + id + "] does not exist in project, remove it from the missing file."); unsafeMappings.remove(id); } unknownDependenciesId.clear(); } // push back loaded dependencies for (Object o : unsafeMappings.keySet()) { String id = (String) o; MavenProject project = artifactCache.get(id); if (project == null) { getLogger().warn("dependency [" + id + "] does not exist in project."); continue; } String license = (String) unsafeMappings.get(id); if (StringUtils.isEmpty(license)) { // empty license means not fill, skip it continue; } // add license in map addLicense(licenseMap, project, license); // remove unknown license unsafeDependencies.remove(project); } if (unsafeDependencies.isEmpty()) { // no more unknown license in map licenseMap.remove(LicenseMap.UNKNOWN_LICENSE_MESSAGE); } else { // add a "with no value license" for missing dependencies for (MavenProject project : unsafeDependencies) { String id = MojoHelper.getArtifactId(project.getArtifact()); if (getLogger().isDebugEnabled()) { getLogger().debug("dependency [" + id + "] has no license, add it in the missing file."); } unsafeMappings.setProperty(id, ""); } } return unsafeMappings; }
From source file:org.kuali.coeus.common.framework.custom.CustomDataHelperBase.java
/** * This method builds the custom data collections used on the form and populates the values from the collection of AwardCustomData on the Award. * @param customAttributeGroups//from w w w.j ava 2s.c o m */ @SuppressWarnings("unchecked") public void buildCustomDataCollectionsOnExistingDocument(SortedMap<String, List> customAttributeGroups) { boolean documentNotRouted = false; documentNotRouted = documentNotRouted(); /* * Going through all customDataDocs and adding the custom ones already in the document */ List<T> customDataInDocument = getCustomDataList(); Set<Entry<String, CustomAttributeDocument>> allCustomAttributeDocuments = getCustomAttributeDocuments() .entrySet(); for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry : allCustomAttributeDocuments) { for (T documentCustomData : customDataInDocument) { if (isMatch(documentCustomData, customAttributeDocumentEntry)) { String groupName = getCustomAttributeDocuments() .get(documentCustomData.getCustomAttributeId().toString()).getCustomAttribute() .getGroupName(); addToGroup(groupName, customAttributeGroups, customAttributeDocumentEntry); break; } } } /* * Go through all the custom data documents and if the document HAS NOT ROUTED and there are new custom data documents available, * add those to the document as well. */ if (documentNotRouted) { for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry : allCustomAttributeDocuments) { List<CustomAttributeDocument> entriesInCurrentGroup = customAttributeGroups .get(customAttributeDocumentEntry.getValue().getCustomAttribute().getGroupName()); if (entriesInCurrentGroup == null || !alreadyExists(entriesInCurrentGroup, customAttributeDocumentEntry)) { String groupName = customAttributeDocumentEntry.getValue().getCustomAttribute().getGroupName(); // create customAttributeDocValues for the new custom data fields. addToCustomDataList(customAttributeDocumentEntry); addToGroup(groupName, customAttributeGroups, customAttributeDocumentEntry); } } } }
From source file:org.opennaas.extensions.genericnetwork.capability.circuitstatistics.CircuitStatisticsCapability.java
private SortedMap<Long, List<CircuitStatistics>> parseCSV(String csvStatistics) throws IllegalArgumentException, IOException { CSVReader reader = new CSVReader(new StringReader(csvStatistics)); try {/*from ww w. j a v a 2s . c o m*/ SortedMap<Long, List<CircuitStatistics>> circuitsStatistics = new TreeMap<Long, List<CircuitStatistics>>(); List<String[]> records = reader.readAll(); log.debug("Storing the new " + records.size() + " received circuits statistics."); for (String[] currentRecord : records) { if (currentRecord.length < 7) throw new IllegalArgumentException( "Invalid record length: it should contain at least 7 fields."); CircuitStatistics currentStatistics = new CircuitStatistics(); if (!StringUtils.isNumeric(currentRecord[0].trim())) throw new IllegalArgumentException("Records should start with timestamp."); Long timestamp = Long.valueOf(currentRecord[0].trim()); currentStatistics.setSlaFlowId(currentRecord[1].trim()); currentStatistics.setThroughput(currentRecord[2].trim()); currentStatistics.setPacketLoss(currentRecord[3].trim()); currentStatistics.setDelay(currentRecord[4].trim()); currentStatistics.setJitter(currentRecord[5].trim()); StringBuilder sb = new StringBuilder(); for (int i = 6; i < currentRecord.length; i++) sb.append(currentRecord[i]).append(","); sb.setLength(sb.length() - 1); // remove last "," currentStatistics.setFlowData(sb.toString().trim()); if (circuitsStatistics.containsKey(timestamp)) circuitsStatistics.get(timestamp).add(currentStatistics); else { List<CircuitStatistics> circuitStatisticsList = new ArrayList<CircuitStatistics>(); circuitStatisticsList.add(currentStatistics); circuitsStatistics.put(timestamp, circuitStatisticsList); } } return circuitsStatistics; } finally { reader.close(); } }
From source file:org.archive.crawler.frontier.WorkQueueFrontier.java
/** * This method compiles a human readable report on the status of the frontier * at the time of the call./*from w w w . j a v a2 s . c o m*/ * @param name Name of report. * @param writer Where to write to. */ @Override public synchronized void reportTo(PrintWriter writer) { int allCount = allQueues.size(); int inProcessCount = inProcessQueues.size(); int readyCount = readyClassQueues.size(); int snoozedCount = getSnoozedCount(); int activeCount = inProcessCount + readyCount + snoozedCount; int inactiveCount = getTotalInactiveQueues(); int retiredCount = getRetiredQueues().size(); int exhaustedCount = allCount - activeCount - inactiveCount - retiredCount; writer.print("Frontier report - "); writer.print(ArchiveUtils.get12DigitDate()); writer.print("\n"); writer.print(" Job being crawled: "); writer.print(controller.getMetadata().getJobName()); writer.print("\n"); writer.print("\n -----===== STATS =====-----\n"); writer.print(" Discovered: "); writer.print(Long.toString(discoveredUriCount())); writer.print("\n"); writer.print(" Queued: "); writer.print(Long.toString(queuedUriCount())); writer.print("\n"); writer.print(" Finished: "); writer.print(Long.toString(finishedUriCount())); writer.print("\n"); writer.print(" Successfully: "); writer.print(Long.toString(succeededFetchCount())); writer.print("\n"); writer.print(" Failed: "); writer.print(Long.toString(failedFetchCount())); writer.print("\n"); writer.print(" Disregarded: "); writer.print(Long.toString(disregardedUriCount())); writer.print("\n"); writer.print("\n -----===== QUEUES =====-----\n"); writer.print(" Already included size: "); writer.print(Long.toString(uriUniqFilter.count())); writer.print("\n"); writer.print(" pending: "); writer.print(Long.toString(uriUniqFilter.pending())); writer.print("\n"); writer.print("\n All class queues map size: "); writer.print(Long.toString(allCount)); writer.print("\n"); writer.print(" Active queues: "); writer.print(activeCount); writer.print("\n"); writer.print(" In-process: "); writer.print(inProcessCount); writer.print("\n"); writer.print(" Ready: "); writer.print(readyCount); writer.print("\n"); writer.print(" Snoozed: "); writer.print(snoozedCount); writer.print("\n"); writer.print(" Inactive queues: "); writer.print(inactiveCount); writer.print(" ("); Map<Integer, Queue<String>> inactives = getInactiveQueuesByPrecedence(); boolean betwixt = false; for (Integer k : inactives.keySet()) { if (betwixt) { writer.print("; "); } writer.print("p"); writer.print(k); writer.print(": "); writer.print(inactives.get(k).size()); betwixt = true; } writer.print(")\n"); writer.print(" Retired queues: "); writer.print(retiredCount); writer.print("\n"); writer.print(" Exhausted queues: "); writer.print(exhaustedCount); writer.print("\n"); State last = lastReachedState; writer.print("\n Last state: " + last); writer.print("\n -----===== MANAGER THREAD =====-----\n"); ToeThread.reportThread(managerThread, writer); writer.print("\n -----===== " + largestQueues.size() + " LONGEST QUEUES =====-----\n"); appendQueueReports(writer, "LONGEST", largestQueues.getEntriesDescending().iterator(), largestQueues.size(), largestQueues.size()); writer.print("\n -----===== IN-PROCESS QUEUES =====-----\n"); Collection<WorkQueue> inProcess = inProcessQueues; ArrayList<WorkQueue> copy = extractSome(inProcess, maxQueuesPerReportCategory); appendQueueReports(writer, "IN-PROCESS", copy.iterator(), copy.size(), maxQueuesPerReportCategory); writer.print("\n -----===== READY QUEUES =====-----\n"); appendQueueReports(writer, "READY", this.readyClassQueues.iterator(), this.readyClassQueues.size(), maxQueuesPerReportCategory); writer.print("\n -----===== SNOOZED QUEUES =====-----\n"); Object[] objs = snoozedClassQueues.toArray(); DelayedWorkQueue[] qs = Arrays.copyOf(objs, objs.length, DelayedWorkQueue[].class); Arrays.sort(qs); appendQueueReports(writer, "SNOOZED", new ObjectArrayIterator(qs), getSnoozedCount(), maxQueuesPerReportCategory); writer.print("\n -----===== INACTIVE QUEUES =====-----\n"); SortedMap<Integer, Queue<String>> sortedInactives = getInactiveQueuesByPrecedence(); for (Integer prec : sortedInactives.keySet()) { Queue<String> inactiveQueues = sortedInactives.get(prec); appendQueueReports(writer, "INACTIVE-p" + prec, inactiveQueues.iterator(), inactiveQueues.size(), maxQueuesPerReportCategory); } writer.print("\n -----===== RETIRED QUEUES =====-----\n"); appendQueueReports(writer, "RETIRED", getRetiredQueues().iterator(), getRetiredQueues().size(), maxQueuesPerReportCategory); writer.flush(); }