List of usage examples for java.util SortedMap get
V get(Object key);
From source file:org.sakaiproject.tool.roster.FilteredParticipantListingBean.java
protected SortedMap<String, Integer> findRoleCounts(Iterable<Participant> participants) { SortedMap<String, Integer> roleCountMap = new TreeMap<String, Integer>(); for (Participant participant : participants) { String role = participant.getRoleTitle(); if (role != null) { if (roleCountMap.containsKey(role)) { int count = roleCountMap.get(role) + 1; roleCountMap.put(role, count); } else { roleCountMap.put(role, 1); }// w w w . j a v a2 s.c om } else { String partName = "Unknown"; //This doesn't seem likely either, but just in case! if (participant.getUser() != null) { partName = participant.getUser().getDisplayId(); } log.info("Role null for participant:" + partName); } } return roleCountMap; }
From source file:kmi.taa.core.PredicateObjectRetriever.java
public void execute(String input, String output, String proxy) throws IOException { BufferedReader br = null;//from ww w . j av a2 s . c om String line = ""; StringBuilder builder = new StringBuilder(); try { br = new BufferedReader(new FileReader(input)); System.out.println(System.currentTimeMillis() + ": retrieving predicate links and objects ..."); Map<Integer, String> originalLines = new LinkedHashMap<>(); int lineId = 1; while ((line = br.readLine()) != null) { originalLines.put(lineId++, line); } System.out.println(System.currentTimeMillis() + ": starting multithreaded retrieving predicates and objects on all slinks ..."); SortedMap<Integer, String> results = retrieveAll(originalLines, proxy); for (Integer id : results.keySet()) { String result = results.get(id); if (!result.equals("")) { String[] pairs = result.split(System.getProperty("line.separator")); for (String po : pairs) { builder.append(originalLines.get(id) + "\t" + po); builder.append(System.lineSeparator()); } } else { builder.append(originalLines.get(id)); builder.append(System.lineSeparator()); } } } finally { if (br != null) { br.close(); } } FileHelper.writeFile(builder.toString(), output, false); System.out.println(System.currentTimeMillis() + ": po retrieving completed"); }
From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java
/** * This method updates the CFDA table with the values received from the * gov site.// w ww. j av a 2 s. c om * @see org.kuali.kra.external.Cfda.CfdaService#updateCfda() */ public CfdaUpdateResults updateCfda() { CfdaUpdateResults updateResults = new CfdaUpdateResults(); StringBuilder message = new StringBuilder(); Map<String, CFDA> govCfdaMap; try { govCfdaMap = retrieveGovCodes(); } catch (IOException ioe) { message.append("Problem encountered while retrieving cfda numbers, " + "the database was not updated." + ioe.getMessage()); updateResults.setMessage(message.toString()); return updateResults; } SortedMap<String, CFDA> kcMap = getCfdaValuesInDatabase(); updateResults.setNumberOfRecordsInKcDatabase(kcMap.size()); updateResults.setNumberOfRecordsRetrievedFromWebSite(govCfdaMap.size()); for (String key : kcMap.keySet()) { CFDA kcCfda = kcMap.get(key); CFDA govCfda = govCfdaMap.get(key); if (kcCfda.getCfdaMaintenanceTypeId().equalsIgnoreCase(Constants.CFDA_MAINT_TYP_ID_MANUAL)) { // Leave it alone. It's maintained manually. updateResults.setNumberOfRecordsNotUpdatedBecauseManual( 1 + updateResults.getNumberOfRecordsNotUpdatedBecauseManual()); } else if (kcCfda.getCfdaMaintenanceTypeId().equalsIgnoreCase(Constants.CFDA_MAINT_TYP_ID_AUTOMATIC)) { if (govCfda == null) { if (kcCfda.getActive()) { kcCfda.setActive(false); businessObjectService.save(kcCfda); updateResults.setNumberOfRecordsDeactivatedBecauseNoLongerOnWebSite( updateResults.getNumberOfRecordsDeactivatedBecauseNoLongerOnWebSite() + 1); } else { // Leave it alone for historical purposes updateResults.setNumberOfRecordsNotUpdatedForHistoricalPurposes( updateResults.getNumberOfRecordsNotUpdatedForHistoricalPurposes() + 1); } } else { if (kcCfda.getActive()) { /*if (!kcCfda.getCfdaProgramTitleName().equalsIgnoreCase(govCfda.getCfdaProgramTitleName())) { message.append("The program title for CFDA " + kcCfda.getCfdaNumber() + " changed from " + kcCfda.getCfdaProgramTitleName() + " to " + govCfda.getCfdaProgramTitleName() + ".<BR>"); }*/ updateResults.setNumberOfRecordsUpdatedBecauseAutomatic( updateResults.getNumberOfRecordsUpdatedBecauseAutomatic() + 1); } else { kcCfda.setActive(true); updateResults .setNumberOfRecordsReActivated(updateResults.getNumberOfRecordsReActivated() + 1); } kcCfda.setCfdaProgramTitleName(govCfda.getCfdaProgramTitleName()); businessObjectService.save(kcCfda); } } // Remove it from the govMap so the remaining codes are new govCfdaMap.remove(key); } // New CFDA number from govt, added to the db updateResults.setMessage(message.toString()); addNew(govCfdaMap); updateResults.setNumberOfRecordsNewlyAddedFromWebSite(govCfdaMap.size() + 1); return updateResults; }
From source file:net.sourceforge.subsonic.controller.WapController.java
public ModelAndView wap(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String username = securityService.getCurrentUsername(request); List<MusicFolder> folders = settingsService.getMusicFoldersForUser(username); if (folders.isEmpty()) { map.put("noMusic", true); } else {//www . j av a 2s .c om SortedMap<MusicIndex, List<MusicIndex.SortableArtistWithMediaFiles>> allArtists = musicIndexService .getIndexedArtists(folders, false); // If an index is given as parameter, only show music files for this index. String index = request.getParameter("index"); if (index != null) { List<MusicIndex.SortableArtistWithMediaFiles> artists = allArtists.get(new MusicIndex(index)); if (artists == null) { map.put("noMusic", true); } else { map.put("artists", artists); } } // Otherwise, list all indexes. else { map.put("indexes", allArtists.keySet()); } } return new ModelAndView("wap/index", "model", map); }
From source file:org.gvnix.web.screen.roo.addon.PatternMetadataProvider.java
/** * Return an instance of the Metadata offered by this add-on. *//*from w w w .j a v a 2 s . c o m*/ @Override protected ItdTypeDetailsProvidingMetadataItem getMetadata(String mid, JavaType aspect, PhysicalTypeMetadata controllerMetadata, String file) { // We need to parse the web scaffold annotation, which we expect to be // present WebScaffoldAnnotationValues webScaffoldAnnotationValues = new WebScaffoldAnnotationValues( controllerMetadata); if (!webScaffoldAnnotationValues.isAnnotationFound() || webScaffoldAnnotationValues.getFormBackingObject() == null || controllerMetadata.getMemberHoldingTypeDetails() == null) { return null; } // Get controller java type from its metadata identification JavaType controllerType = PatternMetadata.getJavaType(mid); // We need to know the metadata of the controller through // WebScaffoldMetada LogicalPath path = PatternMetadata.getPath(mid); String webScaffoldMetadataId = WebScaffoldMetadata.createIdentifier(controllerType, path); WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) getMetadataService() .get(webScaffoldMetadataId); if (webScaffoldMetadata == null) { // The pattern can not be defined over a Controller without // RooWebScaffold return null; } // We know governor type details are non-null and can be safely cast ClassOrInterfaceTypeDetails controllerTypeDetails = (ClassOrInterfaceTypeDetails) controllerMetadata .getMemberHoldingTypeDetails(); Validate.notNull(controllerTypeDetails, "Governor failed to provide class type details, in violation of superclass contract"); // Check if there are pattern names used more than once in project Validate.isTrue(!getPatternService().existsMasterPatternDuplicated(), "There is a pattern name used more than once in the project"); // Get pattern attributes of the controller List<StringAttributeValue> patternList = getPatternService().getControllerMasterPattern(controllerType); // Lookup the form backing object's metadata and check that JavaType entity = webScaffoldAnnotationValues.getFormBackingObject(); // Get and validate required details and metadatas PhysicalTypeMetadata entityMetadata = (PhysicalTypeMetadata) getMetadataService().get( PhysicalTypeIdentifier.createIdentifier(entity, LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""))); Validate.notNull(entityMetadata, "Unable to obtain physical type metadata for type " + entity.getFullyQualifiedTypeName()); MemberDetails entityDetails = getMemberDetails(entityMetadata); MemberHoldingTypeDetails entityPersistentDetails = MemberFindingUtils .getMostConcreteMemberHoldingTypeDetailsWithTag(entityDetails, CustomDataKeys.PERSISTENT_TYPE); SortedMap<JavaType, JavaTypeMetadataDetails> relatedEntities = getWebMetadataService() .getRelatedApplicationTypeMetadata(entity, entityDetails, mid); if (entityPersistentDetails == null || relatedEntities == null || relatedEntities.get(entity) == null || relatedEntities.get(entity).getPersistenceDetails() == null) { return null; } // Remember that this entity JavaType matches up with this metadata // identification string // Start by clearing the previous association // Working in the same way as getWebScaffoldMetadataProvider() JavaType oldEntity = webScaffoldMidToEntityMap.get(mid); if (oldEntity != null) { entityToWebScaffoldMidMap.remove(oldEntity); } entityToWebScaffoldMidMap.put(entity, mid); webScaffoldMidToEntityMap.put(mid, entity); MemberDetails controllerDetails = getMemberDetails(controllerMetadata); Map<JavaSymbolName, DateTimeFormatDetails> entityDateTypes = getWebMetadataService().getDatePatterns(entity, entityDetails, mid); // Install Dialog Bean OperationUtils.installWebDialogClass(aspect.getPackage().getFullyQualifiedPackageName().concat(".dialog"), getProjectOperations().getPathResolver(), getFileManager()); // Related fields and dates SortedMap<JavaType, JavaTypeMetadataDetails> relatedFields = getRelationFieldsDetails(mid, controllerMetadata, entity, getWebMetadataService()); Map<JavaType, Map<JavaSymbolName, DateTimeFormatDetails>> relatedDates = getRelationFieldsDateFormat(mid, controllerMetadata, entity, getWebMetadataService()); // Pass dependencies required by the metadata in through its constructor return new PatternMetadata(mid, aspect, controllerMetadata, controllerDetails, webScaffoldMetadata, patternList, entityMetadata, relatedEntities, relatedFields, relatedDates, entityDateTypes); }
From source file:uk.ac.ucl.excites.sapelli.shared.io.text.CharsetHelpers.java
/** * Parses all .charsetinfo files in the input folder and works out which is the * maximum "maxBytesPerChar" value for each known Charset across all input files. * If this summarised information is in anyway different from the information in * {@link #CharsetMaxMaxBytesPerCharBundle} (or if {@code force} is {@code true}) * then a new CharsetMaxMaxBytesPerChar.properties is created (or overwritten!) * in the output folder./*from ww w . j a va2 s. c o m*/ * * This method is called from a Groovy script in the pom.xml of the Sapelli Library. * * @param inputFolderPath path of a directory containing CharsetInfo files (with *.charsetinfo extension!) to process * @param outputFolderPath path of a (resource) directory in which to create the new/updated CharsetMaxMaxBytesPerChar.properties file * @param force when {@code true} a new CharsetMaxMaxBytesPerChar.properties file will always be generated * @return whether or not a new or updated CharsetMaxMaxBytesPerChar.properties file was created * @throws IOException */ static public final boolean GeneratePropertiesFile(String inputFolderPath, String outputFolderPath, boolean force) throws IOException { File inputFolder = new File(inputFolderPath); if (!inputFolder.isDirectory() || !inputFolder.exists()) throw new IllegalArgumentException("Please provide a valid and existing folder!"); SortedMap<String, String> fileHeaders = new TreeMap<String, String>(); SortedMap<String, Float> tempCN2MBPC = new TreeMap<String, Float>(); // Process all charsetinfo files in the folder: for (File charsetFile : inputFolder .listFiles((FileFilter) new WildcardFileFilter("*." + CHARSETINFO_FILE_EXTENSION))) { try (UnicodeBOMInputStream input = new UnicodeBOMInputStream(new FileInputStream(charsetFile)); BufferedReader reader = new BufferedReader(input.getReader(CHARSETINFO_FILE_CHARSET))) { String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; // skip blank lines if (line.charAt(0) == COMMENT_LINE_MARKER) { if (!fileHeaders.containsKey(charsetFile.getName())) fileHeaders.put(charsetFile.getName(), line.substring(1).trim()); continue; // skip comment lines } // Parse Charset info: CharsetInfo csInfo = CharsetInfo.Parse(line); // Store/replace max maxBytesPerChar value: if (csInfo.maxBytesPerChar > 0.0f && (!tempCN2MBPC.containsKey(csInfo.name) || tempCN2MBPC.get(csInfo.name).floatValue() < csInfo.maxBytesPerChar)) tempCN2MBPC.put(csInfo.name, csInfo.maxBytesPerChar); } if (!fileHeaders.containsKey(charsetFile.getName())) fileHeaders.put(charsetFile.getName(), ""); } } // Compare information loaded from charsetinfo files with that in the resource bundle: boolean different = force || CharsetMaxMaxBytesPerCharBundle == null || tempCN2MBPC.size() != getNumberOfKnownCharsets(); if (!different) for (Map.Entry<String, Float> mapping : tempCN2MBPC.entrySet()) try { if (!Float.valueOf(CharsetMaxMaxBytesPerCharBundle.getString(mapping.getKey())) .equals(mapping.getValue())) // getString throws Exception if key is not found throw new Exception("maxBytesPerChar mismatch!"); } catch (Exception e) { different = true; break; } // If the information is different... if (different) { // Write new properties file (in package-specific subfolder of the given output folder): File outputFolder = new File(new File(outputFolderPath), ClassHelpers.classPackageAsResourcePath(CharsetHelpers.class)); FileHelpers.createDirectory(outputFolder); try (FileOutputStream fos = new FileOutputStream( new File(outputFolder, CMMBPC_PROPERTIES_FILE_NAME + "." + PROPERTIES_FILE_EXTENSION)); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(fos, PROPERTIES_FILE_CHARSET))) { // Header: writer.write(COMMENT_LINE_MARKER + " Generated on " + TimeUtils.getISOTimestamp(System.currentTimeMillis(), false) + " from input files:" + EOL); for (Map.Entry<String, String> fileAndHeader : fileHeaders.entrySet()) { writer.write(COMMENT_LINE_MARKER + "\t- " + fileAndHeader.getKey() + ":" + EOL); writer.write(COMMENT_LINE_MARKER + "\t\t" + fileAndHeader.getValue() + EOL); } writer.write(EOL); // Body: for (Map.Entry<String, Float> mapping : tempCN2MBPC.entrySet()) writer.write(mapping.getKey() + "=" + mapping.getValue().toString() + EOL); } } return different; }
From source file:com.aurel.track.exchange.importer.MsProjectImportActionTest.java
/** * This method executes the ms project file import. In case if needed handles resource mappings. *///from w w w.j a v a2s. c o m @Test public void testSubmitResourceMapping() { try { File msProjectFolder = new File(MS_PROJECT_FILES_PATH); File[] listOfFiles = msProjectFolder.listFiles(); for (File fileToUpload : listOfFiles) { if (fileToUpload.isFile()) { System.out.println("Testing the following Ms. project file: " + fileToUpload.getName()); File tempFile = new File( msProjectFolder + "/" + FilenameUtils.removeExtension(fileToUpload.getName()) + "Tmp." + FilenameUtils.getExtension(fileToUpload.getName())); Files.copy(fileToUpload, tempFile); MsProjectExchangeDataStoreBean msProjectExchangeDataStoreBean; msProjectExchangeDataStoreBean = MsProjectExchangeBL.initMsProjectExchangeBeanForImport( PROJECT_OR_RELEASE_ID, PersonBL.loadByPrimaryKey(1), tempFile, null); SortedMap<String, Integer> resourceNameToResourceUIDMap = MsProjectImporterBL .getResourceNameToResourceUIDMap(msProjectExchangeDataStoreBean.getWorkResources()); Map<Integer, Integer> resourceUIDToPersonIDMap = new HashMap<Integer, Integer>(); for (String key : resourceNameToResourceUIDMap.keySet()) { resourceUIDToPersonIDMap.put(resourceNameToResourceUIDMap.get(key), DEFAULT_PERSON_ID); } sessionMap.put("msProjectImporterBean", msProjectExchangeDataStoreBean); ActionProxy actionProxy = getActionProxy("/msProjectImport!submitResourceMapping.action"); actionProxy.getInvocation().getInvocationContext().setSession(sessionMap); String result = actionProxy.execute(); String responseText = response.getContentAsString(); assertTrue(responseText.length() > 0); assertNotNull(responseText); System.out.println("Test method name: submitResourceMapping result: " + result + " response: " + responseText); deleteProjectTasks(); if (tempFile.exists()) { tempFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step6GraphTransitivityCleaner.java
@SuppressWarnings("unchecked") public static void printResultStatistics(File xmlFile) throws IllegalAccessException { Map<String, Map<String, GraphCleaningResults>> results = (Map<String, Map<String, GraphCleaningResults>>) XStreamTools .getXStream().fromXML(xmlFile); // System.out.println(results); SortedMap<String, List<GraphCleaningResults>> resultsGroupedByMethod = new TreeMap<>(); for (Map.Entry<String, Map<String, GraphCleaningResults>> entry : results.entrySet()) { // System.out.println(entry.getKey()); for (Map.Entry<String, GraphCleaningResults> e : entry.getValue().entrySet()) { // System.out.println(e.getKey()); // System.out.println(e.getValue()); if (!resultsGroupedByMethod.containsKey(e.getKey())) { resultsGroupedByMethod.put(e.getKey(), new ArrayList<GraphCleaningResults>()); }//from www. j ava 2 s . c om resultsGroupedByMethod.get(e.getKey()).add(e.getValue()); } } String header = null; // collect statistics for (Map.Entry<String, List<GraphCleaningResults>> entry : resultsGroupedByMethod.entrySet()) { List<GraphCleaningResults> value = entry.getValue(); SortedMap<String, DescriptiveStatistics> stringDescriptiveStatisticsMap = collectStatisticsOverGraphCleaningResults( value); if (header == null) { header = StringUtils.join(stringDescriptiveStatisticsMap.keySet(), "\t"); System.out.println("\t\t" + header); } List<Double> means = new ArrayList<>(); List<Double> stdDevs = new ArrayList<>(); for (DescriptiveStatistics statistics : stringDescriptiveStatisticsMap.values()) { means.add(statistics.getMean()); stdDevs.add(statistics.getStandardDeviation()); } List<String> meansString = new ArrayList<>(); for (Double mean : means) { meansString.add(String.format(Locale.ENGLISH, "%.2f", mean)); } List<String> stdDevString = new ArrayList<>(); for (Double stdDev : stdDevs) { stdDevString.add(String.format(Locale.ENGLISH, "%.2f", stdDev)); } System.out.println(entry.getKey() + "\tmean\t" + StringUtils.join(meansString, "\t")); // System.out.println(entry.getKey() + "\tstdDev\t" + StringUtils.join(stdDevString, "\t")); } }
From source file:co.rsk.peg.BridgeStorageProviderTest.java
@Test public void createSaveAndRecreateInstanceWithTxsWaitingForSignatures() throws IOException { BtcTransaction tx1 = createTransaction(); BtcTransaction tx2 = createTransaction(); BtcTransaction tx3 = createTransaction(); Sha3Hash hash1 = PegTestUtils.createHash3(); Sha3Hash hash2 = PegTestUtils.createHash3(); Sha3Hash hash3 = PegTestUtils.createHash3(); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); BridgeStorageProvider provider0 = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR); provider0.getRskTxsWaitingForSignatures().put(hash1, tx1); provider0.getRskTxsWaitingForSignatures().put(hash2, tx2); provider0.getRskTxsWaitingForSignatures().put(hash3, tx3); provider0.save();/*from w w w . j av a2s . c o m*/ track.commit(); track = repository.startTracking(); BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR); SortedMap<Sha3Hash, BtcTransaction> signatures = provider.getRskTxsWaitingForSignatures(); Assert.assertNotNull(signatures); Assert.assertTrue(signatures.containsKey(hash1)); Assert.assertTrue(signatures.containsKey(hash2)); Assert.assertTrue(signatures.containsKey(hash3)); Assert.assertEquals(tx1.getHash(), signatures.get(hash1).getHash()); Assert.assertEquals(tx2.getHash(), signatures.get(hash2).getHash()); Assert.assertEquals(tx3.getHash(), signatures.get(hash3).getHash()); }
From source file:org.openmrs.module.rwandaprimarycare.AllEncountersController.java
@RequestMapping("/module/rwandaprimarycare/allEncounters") public String listAllEncounters(@RequestParam("patientId") int patientId, ModelMap model) throws PrimaryCareException { //LK: Need to ensure that all primary care methods only throw a PrimaryCareException //So that errors will be directed to a touch screen error page try {/*w w w. j a v a 2s .c o m*/ Patient patient = Context.getPatientService().getPatient(patientId); SortedMap<Date, List<Encounter>> encounters = new TreeMap<Date, List<Encounter>>( Collections.reverseOrder()); for (Encounter e : Context.getEncounterService().getEncountersByPatient(patient)) { Calendar cal = Calendar.getInstance(); cal.setTime(e.getEncounterDatetime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date day = cal.getTime(); List<Encounter> holder = encounters.get(day); if (holder == null) { holder = new ArrayList<Encounter>(); encounters.put(day, holder); } holder.add(e); } model.addAttribute("patient", patient); model.addAttribute("encounters", encounters); model.addAttribute("vitalsEncounterType", PrimaryCareBusinessLogic.getVitalsEncounterType()); model.addAttribute("registrationEncounterType", PrimaryCareBusinessLogic.getRegistrationEncounterType()); } catch (Exception e) { throw new PrimaryCareException(e); } return "/module/rwandaprimarycare/allEncounters"; }