List of usage examples for java.util TreeMap put
public V put(K key, V value)
From source file:FastTreeMap.java
/** * Associate the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced and returned./*from w w w.j a v a 2 s. co m*/ * * @param key the key with which the value is to be associated * @param value the value to be associated with this key * @return the value previously mapped to the key, or null */ public Object put(Object key, Object value) { if (fast) { synchronized (this) { TreeMap temp = (TreeMap) map.clone(); Object result = temp.put(key, value); map = temp; return (result); } } else { synchronized (map) { return (map.put(key, value)); } } }
From source file:com.sfs.whichdoctor.dao.AddressVerificationDAOImpl.java
/** * Creates the address verification bean. * * @param address the address// w w w . j ava 2 s . c o m * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final AddressBean address) throws WhichDoctorDaoException { if (address == null) { throw new WhichDoctorDaoException("The address cannot be null"); } if (address.getGUID() < 1) { throw new WhichDoctorDaoException("The address requires a valid GUID"); } if (StringUtils.isBlank(address.getCountry())) { throw new WhichDoctorDaoException("A valid country is required"); } if (StringUtils.isBlank(address.getAddressField(0))) { throw new WhichDoctorDaoException("An address requires at least one line"); } // The message for any unprocessed records String processedMessage = "Address verification request superceeded by " + "a WhichDoctor change"; // Load the parent person or organisation int personIdentifier = 0; String personName = ""; String organisationName = ""; boolean parentFound = false; try { PersonBean person = this.personDAO.loadGUID(address.getReferenceGUID()); if (person != null) { personIdentifier = person.getPersonIdentifier(); personName = person.getPreferredName() + " " + person.getLastName(); parentFound = true; } } catch (WhichDoctorDaoException wde) { dataLogger.info("No person found for the address: " + wde.getMessage()); } if (!parentFound) { try { OrganisationBean org = this.organisationDAO.loadGUID(address.getReferenceGUID()); if (org != null) { organisationName = org.getName(); parentFound = true; } } catch (WhichDoctorDaoException wde) { dataLogger.info("No organisation found for the address: " + wde.getMessage()); } } if (!parentFound) { throw new WhichDoctorDaoException( "No valid person or organisation is " + "associated with this address"); } /* Identify the pending and processed ProcessStatusId */ int pendingProcessStatusId = 0; int processedProcessStatusId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Address Verification Process Status", "", PENDING); pendingProcessStatusId = object.getObjectTypeId(); } catch (SFSDaoException sfe) { dataLogger.error("Error loading address verification process status: " + sfe.getMessage()); throw new WhichDoctorDaoException("A valid address verification process status is required"); } try { ObjectTypeBean object = this.getObjectTypeDAO().load("Address Verification Process Status", "", PROCESSED); processedProcessStatusId = object.getObjectTypeId(); } catch (SFSDaoException sfe) { dataLogger.error("Error loading address verification process status: " + sfe.getMessage()); throw new WhichDoctorDaoException("A valid address verification process status is required"); } int addressVerificationId = 0; int createCount = 0; // Create the new record Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); TreeMap<Integer, String> addressMap = new TreeMap<Integer, String>(); addressMap.put(0, address.getAddressField(0)); addressMap.put(1, address.getAddressField(1)); addressMap.put(2, address.getAddressField(2)); addressMap.put(3, address.getAddressField(3)); addressMap.put(4, address.getAddressField(4)); addressMap.put(5, address.getAddressField(5)); // Remove the suburb and city values from the map addressMap.put(address.getAddressFieldCount() - 1, ""); addressMap.put(address.getAddressFieldCount() - 2, ""); try { createCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("addressVerification/create"), new Object[] { address.getGUID(), address.getReferenceGUID(), personIdentifier, personName, organisationName, pendingProcessStatusId, sqlTimeStamp, addressMap.get(0), addressMap.get(1), addressMap.get(2), addressMap.get(3), addressMap.get(4), addressMap.get(5), address.getSuburb(), address.getCity(), address.getStateAbbreviation(), address.getCountry(), address.getPostCode() }); } catch (DataAccessException de) { dataLogger.error("Error creating address verification record: " + de.getMessage()); throw new WhichDoctorDaoException( "Error creating address verification " + "record: " + de.getMessage()); } if (createCount > 0) { // Find the maximum address verification id addressVerificationId = this.getJdbcTemplateReader() .queryForInt(this.getSQL().getValue("addressVerification/findMax")); // Set the processed flag to true for any pending address // verification records for this address guid this.getJdbcTemplateWriter().update(this.getSQL().getValue("addressVerification/updateProcess"), new Object[] { processedProcessStatusId, processedMessage, address.getGUID(), addressVerificationId, pendingProcessStatusId }); // Update the address verification status this.addressDAO.updateVerificationStatus("Pending verification", address.getGUID()); } return addressVerificationId; }
From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java
public ArrayList<ClassifyOutput> sortByRank(HashMap<ClassifyOutput, Integer> inputList) { LOG.debug("[sortByRank] - BEGIN"); ArrayList<ClassifyOutput> result = new ArrayList<>(); LinkedMap apacheMap = new LinkedMap(inputList); for (int i = 0; i < apacheMap.size() - 1; i++) { TreeMap<Float, ClassifyOutput> treeMap = new TreeMap<>(Collections.reverseOrder()); do {/* w w w . j a v a 2 s.c o m*/ i++; treeMap.put(Float.valueOf(((ClassifyOutput) apacheMap.get(i - 1)).getScore()), (ClassifyOutput) apacheMap.get(i - 1)); } while (i < apacheMap.size() && apacheMap.getValue(i) == apacheMap.getValue(i - 1)); i--; for (Float score : treeMap.keySet()) { result.add(treeMap.get(score)); } } LOG.debug("[sortByRank] - END"); return result; }
From source file:edu.cmu.cs.lti.discoursedb.annotation.brat.io.BratService.java
/** * Parses the offsets file and provides a Map from offset to discoursedb id. This is used to * identify discoursedb entities by offset in order to identify the contribution at a specific point in the aggated (thread-level) document. * /*from w w w .j av a 2 s . c om*/ * @param offsetFile file with the offset mapping * @return a TreeMap (has to be a TreeMap because of the required floorEntry method) mapping offset values to entity ids for the given entity type * @throws IOException if an exception occurred while accessing the offset file */ private TreeMap<Integer, OffsetInfo> getOffsetToOffsetInfoMap(File offsetFile) throws IOException { Assert.notNull(offsetFile, "OffsetFile has to be specified."); TreeMap<Integer, OffsetInfo> offsetToOffsetInfo = new TreeMap<>(); for (String line : FileUtils.readLines(offsetFile)) { OffsetInfo info = new OffsetInfo(line); offsetToOffsetInfo.put(info.getSpanOffset(), info); } return offsetToOffsetInfo; }
From source file:api.wiki.WikiNameApi2.java
private TreeMap<String, String> getCategoryOption(String title) { String query = BASE_URL + "&list=categorymembers&cmlimit=500&cmtitle=" + title + "&cmtype=subcat&cmprop=title"; TreeMap<String, String> values = new TreeMap<>(); try {/*from w w w. j a v a 2 s . c om*/ URL url = new URL(query); File file = File.createTempFile("WIKI_", title); FileUtils.copyURLToFile(url, file); String s = FileUtils.readFileToString(file); JSONArray json = new JSONObject(s).getJSONObject("query").getJSONArray("categorymembers"); for (int i = 0; i < json.length(); i++) { String value = json.getJSONObject(i).getString("title"); String key = value.replaceAll("Category:", "").replaceAll("given names", "").trim(); values.put(key, value); } } catch (IOException ex) { Logger.getLogger(WikiNameApi2.class.getName()).log(Level.SEVERE, null, ex); } return values; }
From source file:org.outofbits.sesame.schemagen.SchemaGeneration.java
/** * Generates the body of the class that shall be created. At first the base namespace will be * detected. If the base namespace is given in the {@link VocabularyOptions}, this namespace * will be preferred. An {@link SchemaGenerationException} will be thrown, if the namespace * cannot be detected automatically.//from ww w . ja v a 2 s . co m * * @param vocabModel {@link Model} that contains all statements of the vocabulary for which the * class shall be created. * @return the body of the class in form of a string. * @throws SchemaGenerationException if the body of the class cannot be generated. */ private String generateClassBody(Resource rootResource, Model vocabModel) throws StringMapFormatter.StringMapFormatterException, SchemaGenerationException { assert vocabModel != null; Map<String, String> classBodyValueMap = new HashMap<>(formattingMap); // Detect the base namespace String basenameSpace; if (vocabularyOptions.baseNamespace() != null) { basenameSpace = vocabularyOptions.baseNamespace(); } else { basenameSpace = detectBaseNamespace(vocabModel, rootResource); if (basenameSpace == null) { if (rootResource != null) { basenameSpace = rootResource.stringValue(); } else { throw new SchemaGenerationException( "The base namespace could not be detected. Please specify it manually."); } } } // Detect the preferred prefix String prefix = null; if (vocabularyOptions.preferredPrefix() != null) { prefix = vocabularyOptions.preferredPrefix(); } else { for (Namespace ns : vocabModel.getNamespaces()) { if (ns.getName().equals(basenameSpace)) { prefix = ns.getPrefix(); break; } } } // Declaration of resources Pattern nsPattern = Pattern.compile(String.format("%s(.+)", basenameSpace)); TreeMap<String, Resource> resourceMap = new TreeMap<>(); for (Resource subject : vocabModel.subjects()) { Matcher matcher = nsPattern.matcher(subject.stringValue()); if (matcher.find()) { resourceMap.put(JavaIdentifier.getJavaIdFrom(matcher.group(1)), subject); } } // Definition and declaration of resources. StringBuilder declarationStringBuilder = new StringBuilder(); StringBuilder definitionStringBuilder = new StringBuilder( stringMapFormatter.format(DEFAULT_VALUE_FACTORY_TEMPLATE, formattingMap)); for (Map.Entry<String, Resource> entry : resourceMap.entrySet()) { Resource subject = entry.getValue(); Map<String, String> valueMap = new HashMap<>(formattingMap); valueMap.put("resource-name", entry.getKey()); valueMap.put("resource-iri", subject.stringValue()); valueMap.put("resource-label", getFirstLiteralFor(vocabModel, subject, LABEL_PROPERTIES).orElse(entry.getKey())); valueMap.put("resource-comment", getFirstLiteralFor(vocabModel, subject, COMMENT_PROPERTIES).orElse("")); declarationStringBuilder.append(stringMapFormatter.format(DEFAULT_RESOURCE_DEC_TEMPLATE, valueMap)); definitionStringBuilder.append(stringMapFormatter.format(DEFAULT_RESOURCE_DEF_TEMPLATE, valueMap)); } classBodyValueMap.put("resource-declarations", declarationStringBuilder.toString()); classBodyValueMap.put("resource-definitions", definitionStringBuilder.toString()); // Namespace and prefix. Map<String, String> valueMap = new HashMap<>(formattingMap); valueMap.put("namespace-iri", basenameSpace); valueMap.put("prefix", prefix); classBodyValueMap.put("namespace", stringMapFormatter.format(DEFAULT_NAMESPACE_TEMPLATE, valueMap)); classBodyValueMap.put("prefix", prefix == null ? "" : stringMapFormatter.format(DEFAULT_PREFIX_TEMPLATE, valueMap)); return stringMapFormatter.format(DEFAULT_CLASS_BODY_TEMPLATE, classBodyValueMap); }
From source file:com.mirth.connect.client.ui.alert.AlertChannelPane.java
public void setChannels(AlertChannels alertChannels, boolean includeConnectors) { if (PlatformUI.MIRTH_FRAME.channelPanel.getCachedChannelStatuses() != null) { TreeMap<String, Channel> channelMap = new TreeMap<String, Channel>(String.CASE_INSENSITIVE_ORDER); // Sort the channels by channel name for (ChannelStatus channelStatus : PlatformUI.MIRTH_FRAME.channelPanel.getCachedChannelStatuses() .values()) {//from w w w . j a va 2 s . co m Channel channel = channelStatus.getChannel(); channelMap.put(channel.getName(), channel); } ChannelTreeTableModel model = (ChannelTreeTableModel) channelTreeTable.getTreeTableModel(); model.addChannels(channelMap.values(), alertChannels, includeConnectors); } enableButton.setEnabled(false); disableButton.setEnabled(false); }
From source file:com.nextgis.rehacompdemo.RoutingActivity.java
private TreeMap<Long, String> getRouteSteps() { TreeMap<Long, String> steps = new TreeMap<>(); try {//from ww w . j a va 2 s .c o m JSONObject jsonObj = new JSONObject(getGeoJSON(mPoints)); JSONArray jsonStepsArray = jsonObj.getJSONArray("features"); JSONObject jsonStep; for (int i = 0; i < jsonStepsArray.length(); i++) { jsonStep = jsonStepsArray.getJSONObject(i).getJSONObject("properties"); steps.put(jsonStepsArray.getJSONObject(i).getLong("id"), jsonStep.getString("instr")); } } catch (Exception e) { e.printStackTrace(); } return steps;//.values().toArray(new String[steps.size()]); }
From source file:com.sfs.whichdoctor.importer.ExamImporter.java
/** * Gets the description map.//w ww .ja v a 2 s . co m * * @return the description map */ public final TreeMap<String, List<String>> getDescriptionMap() { TreeMap<String, List<String>> descriptionMap = new TreeMap<String, List<String>>(); HashMap<Object, List<Object>> beanMap = this.getBeanMap(); for (Object objPerson : beanMap.keySet()) { PersonBean person = (PersonBean) objPerson; String indexDescription = getIndexDescription(person); List<String> descriptions = new ArrayList<String>(); for (Object objExam : beanMap.get(person)) { ExamBean exam = (ExamBean) objExam; descriptions.add(getValueDescription(exam)); } descriptionMap.put(indexDescription, descriptions); } return descriptionMap; }
From source file:com.netxforge.oss2.config.AmiPeerFactory.java
/** * Combine specific and range elements so that AMIPeerFactory has to spend * less time iterating all these elements. * TODO This really should be pulled up into PeerFactory somehow, but I'm not sure how (given that "Definition" is different for both * SNMP and AMI. Maybe some sort of visitor methodology would work. The basic logic should be fine as it's all IP address manipulation * * @throws UnknownHostException//from w ww . j a v a 2 s .com */ void optimize() throws UnknownHostException { getWriteLock().lock(); try { // First pass: Remove empty definition elements for (final Iterator<Definition> definitionsIterator = m_config.getDefinitionCollection() .iterator(); definitionsIterator.hasNext();) { final Definition definition = definitionsIterator.next(); if (definition.getSpecificCount() == 0 && definition.getRangeCount() == 0) { LogUtils.debugf(this, "optimize: Removing empty definition element"); definitionsIterator.remove(); } } // Second pass: Replace single IP range elements with specific elements for (Definition definition : m_config.getDefinitionCollection()) { for (Iterator<Range> rangesIterator = definition.getRangeCollection().iterator(); rangesIterator .hasNext();) { Range range = rangesIterator.next(); if (range.getBegin().equals(range.getEnd())) { definition.addSpecific(range.getBegin()); rangesIterator.remove(); } } } // Third pass: Sort specific and range elements for improved XML // readability and then combine them into fewer elements where possible for (final Definition definition : m_config.getDefinitionCollection()) { // Sort specifics final TreeMap<InetAddress, String> specificsMap = new TreeMap<InetAddress, String>( new InetAddressComparator()); for (final String specific : definition.getSpecificCollection()) { specificsMap.put(InetAddressUtils.getInetAddress(specific), specific.trim()); } // Sort ranges final TreeMap<InetAddress, Range> rangesMap = new TreeMap<InetAddress, Range>( new InetAddressComparator()); for (final Range range : definition.getRangeCollection()) { rangesMap.put(InetAddressUtils.getInetAddress(range.getBegin()), range); } // Combine consecutive specifics into ranges InetAddress priorSpecific = null; Range addedRange = null; for (final InetAddress specific : specificsMap.keySet()) { if (priorSpecific == null) { priorSpecific = specific; continue; } if (BigInteger.ONE.equals(InetAddressUtils.difference(specific, priorSpecific)) && InetAddressUtils.inSameScope(specific, priorSpecific)) { if (addedRange == null) { addedRange = new Range(); addedRange.setBegin(InetAddressUtils.toIpAddrString(priorSpecific)); rangesMap.put(priorSpecific, addedRange); specificsMap.remove(priorSpecific); } addedRange.setEnd(InetAddressUtils.toIpAddrString(specific)); specificsMap.remove(specific); } else { addedRange = null; } priorSpecific = specific; } // Move specifics to ranges for (final InetAddress specific : new ArrayList<InetAddress>(specificsMap.keySet())) { for (final InetAddress begin : new ArrayList<InetAddress>(rangesMap.keySet())) { if (!InetAddressUtils.inSameScope(begin, specific)) { continue; } if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE) .compareTo(InetAddressUtils.toInteger(specific)) > 0) { continue; } final Range range = rangesMap.get(begin); final InetAddress end = InetAddressUtils.getInetAddress(range.getEnd()); if (InetAddressUtils.toInteger(end).add(BigInteger.ONE) .compareTo(InetAddressUtils.toInteger(specific)) < 0) { continue; } if (InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(begin)) >= 0 && InetAddressUtils.toInteger(specific) .compareTo(InetAddressUtils.toInteger(end)) <= 0) { specificsMap.remove(specific); break; } if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE) .equals(InetAddressUtils.toInteger(specific))) { rangesMap.remove(begin); rangesMap.put(specific, range); range.setBegin(InetAddressUtils.toIpAddrString(specific)); specificsMap.remove(specific); break; } if (InetAddressUtils.toInteger(end).add(BigInteger.ONE) .equals(InetAddressUtils.toInteger(specific))) { range.setEnd(InetAddressUtils.toIpAddrString(specific)); specificsMap.remove(specific); break; } } } // Combine consecutive ranges Range priorRange = null; InetAddress priorBegin = null; InetAddress priorEnd = null; for (final Iterator<InetAddress> rangesIterator = rangesMap.keySet().iterator(); rangesIterator .hasNext();) { final InetAddress beginAddress = rangesIterator.next(); final Range range = rangesMap.get(beginAddress); final InetAddress endAddress = InetAddressUtils.getInetAddress(range.getEnd()); if (priorRange != null) { if (InetAddressUtils.inSameScope(beginAddress, priorEnd) && InetAddressUtils .difference(beginAddress, priorEnd).compareTo(BigInteger.ONE) <= 0) { priorBegin = new InetAddressComparator().compare(priorBegin, beginAddress) < 0 ? priorBegin : beginAddress; priorRange.setBegin(InetAddressUtils.toIpAddrString(priorBegin)); priorEnd = new InetAddressComparator().compare(priorEnd, endAddress) > 0 ? priorEnd : endAddress; priorRange.setEnd(InetAddressUtils.toIpAddrString(priorEnd)); rangesIterator.remove(); continue; } } priorRange = range; priorBegin = beginAddress; priorEnd = endAddress; } // Update changes made to sorted maps definition.setSpecific(specificsMap.values().toArray(new String[0])); definition.setRange(rangesMap.values().toArray(new Range[0])); } } finally { getWriteLock().unlock(); } }