List of usage examples for java.util HashMap containsKey
public boolean containsKey(Object key)
From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddAssociatedConceptGenerator.java
private List<AssociatedConceptInfo> getAssociatedConceptInfo(List<Individual> concepts, VitroRequest vreq) { List<AssociatedConceptInfo> info = new ArrayList<AssociatedConceptInfo>(); for (Individual conceptIndividual : concepts) { boolean userGenerated = true; //Note that this isn't technically String conceptUri = conceptIndividual.getURI(); String conceptLabel = conceptIndividual.getName(); //Check if defined by an external vocabulary source List<ObjectPropertyStatement> vocabList = conceptIndividual .getObjectPropertyStatements(RDFS.isDefinedBy.getURI()); String vocabSource = null; String vocabLabel = null; if (vocabList != null && vocabList.size() > 0) { userGenerated = false;//w w w . j a v a2 s .c o m vocabSource = vocabList.get(0).getObjectURI(); Individual sourceIndividual = EditConfigurationUtils.getIndividual(vreq, vocabSource); //Assuming name will get label vocabLabel = sourceIndividual.getName(); } if (userGenerated) { //if the concept in question is skos - which would imply a user generated concept info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, null, null, SKOSConceptType, null, null)); } else { String conceptSemanticTypeURI = null; String conceptSemanticTypeLabel = null; //Can a concept have multiple semantic types? Currently we are only returning the first one //TODO: Change this into a sparql query that returns all types for the concept that are subclasses of SKOS concepts HashMap<String, String> typeAndLabel = this.getConceptSemanticTypeQueryResults( conceptIndividual.getURI(), ModelAccess.on(vreq).getOntModel()); if (typeAndLabel.containsKey("semanticTypeURI")) { conceptSemanticTypeURI = typeAndLabel.get("semanticTypeURI"); } if (typeAndLabel.containsKey("semanticTypeLabel")) { conceptSemanticTypeLabel = typeAndLabel.get("semanticTypeLabel"); } //Assuming this is from an external vocabulary source info.add(new AssociatedConceptInfo(conceptLabel, conceptUri, vocabSource, vocabLabel, null, conceptSemanticTypeURI, conceptSemanticTypeLabel)); } } return info; }
From source file:edu.usc.ir.geo.gazetteer.GeoNameResolver.java
private HashMap<String, List<Location>> resolveEntities(List<String> locationNames, int count, IndexReader reader) throws IOException { if (locationNames.size() >= 200) hitsPerPage = 5; // avoid heavy computation IndexSearcher searcher = new IndexSearcher(reader); Query q = null;// w w w . ja va 2 s . co m HashMap<String, List<Location>> allCandidates = new HashMap<String, List<Location>>(); for (String name : locationNames) { if (!allCandidates.containsKey(name)) { try { //query is wrapped in additional quotes (") to avoid query tokenization on space q = new MultiFieldQueryParser(new String[] { FIELD_NAME_NAME, FIELD_NAME_ALTERNATE_NAMES }, analyzer).parse(String.format("\"%s\"", name)); //sort descending on population SortField populationSort = new SortedNumericSortField(FIELD_NAME_POPULATION, SortField.Type.LONG, true); Sort sort = new Sort(populationSort); //Fetch 3 times desired values, these will be sorted on code and only desired number will be kept ScoreDoc[] hits = searcher.search(q, hitsPerPage * 3, sort).scoreDocs; List<Location> topHits = new ArrayList<Location>(); for (int i = 0; i < hits.length; ++i) { Location tmpLocObj = new Location(); int docId = hits[i].doc; Document d; try { d = searcher.doc(docId); tmpLocObj.setName(d.get(FIELD_NAME_NAME)); tmpLocObj.setLongitude(d.get(FIELD_NAME_LONGITUDE)); tmpLocObj.setLatitude(d.get(FIELD_NAME_LATITUDE)); //If alternate names are empty put name as actual name //This covers missing data and equals weight for later computation if (d.get(FIELD_NAME_ALTERNATE_NAMES).isEmpty()) { tmpLocObj.setAlternateNames(d.get(FIELD_NAME_NAME)); } else { tmpLocObj.setAlternateNames(d.get(FIELD_NAME_ALTERNATE_NAMES)); } tmpLocObj.setCountryCode(d.get(FIELD_NAME_COUNTRY_CODE)); tmpLocObj.setAdmin1Code(d.get(FIELD_NAME_ADMIN1_CODE)); tmpLocObj.setAdmin2Code(d.get(FIELD_NAME_ADMIN2_CODE)); tmpLocObj.setFeatureCode(d.get(FIELD_NAME_FEATURE_CODE)); } catch (IOException e) { e.printStackTrace(); } topHits.add(tmpLocObj); } //Picking hitsPerPage number of locations from feature code sorted list allCandidates.put(name, pickTopSortedByCode(topHits, hitsPerPage)); } catch (org.apache.lucene.queryparser.classic.ParseException e) { e.printStackTrace(); } } } HashMap<String, List<Location>> resolvedEntities = new HashMap<String, List<Location>>(); pickBestCandidates(resolvedEntities, allCandidates, count); return resolvedEntities; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.listing.PropertyWebappsListingController.java
public void doGet(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTIONS)) { return;//from ww w . j a va 2 s . c om } VitroRequest vrequest = new VitroRequest(request); String noResultsMsgStr = "No object properties found"; String ontologyUri = request.getParameter("ontologyUri"); ObjectPropertyDao dao = vrequest.getFullWebappDaoFactory().getObjectPropertyDao(); PropertyInstanceDao piDao = vrequest.getFullWebappDaoFactory().getPropertyInstanceDao(); VClassDao vcDao = vrequest.getFullWebappDaoFactory().getVClassDao(); PropertyGroupDao pgDao = vrequest.getFullWebappDaoFactory().getPropertyGroupDao(); String vclassURI = request.getParameter("vclassUri"); List props = new ArrayList(); if (request.getParameter("propsForClass") != null) { noResultsMsgStr = "There are no properties that apply to this class."; // incomplete list of classes to check, but better than before List<String> superclassURIs = vcDao.getAllSuperClassURIs(vclassURI); superclassURIs.add(vclassURI); superclassURIs.addAll(vcDao.getEquivalentClassURIs(vclassURI)); Map<String, PropertyInstance> propInstMap = new HashMap<String, PropertyInstance>(); for (String classURI : superclassURIs) { Collection<PropertyInstance> propInsts = piDao.getAllPropInstByVClass(classURI); for (PropertyInstance propInst : propInsts) { propInstMap.put(propInst.getPropertyURI(), propInst); } } List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>(); propInsts.addAll(propInstMap.values()); Collections.sort(propInsts); Iterator propInstIt = propInsts.iterator(); HashSet propURIs = new HashSet(); while (propInstIt.hasNext()) { PropertyInstance pi = (PropertyInstance) propInstIt.next(); if (!(propURIs.contains(pi.getPropertyURI()))) { propURIs.add(pi.getPropertyURI()); ObjectProperty prop = (ObjectProperty) dao.getObjectPropertyByURI(pi.getPropertyURI()); if (prop != null) { props.add(prop); } } } } else { props = (request.getParameter("iffRoot") != null) ? dao.getRootObjectProperties() : dao.getAllObjectProperties(); } OntologyDao oDao = vrequest.getFullWebappDaoFactory().getOntologyDao(); HashMap<String, String> ontologyHash = new HashMap<String, String>(); Iterator propIt = props.iterator(); List<ObjectProperty> scratch = new ArrayList(); while (propIt.hasNext()) { ObjectProperty p = (ObjectProperty) propIt.next(); if (p.getNamespace() != null) { if (!ontologyHash.containsKey(p.getNamespace())) { Ontology o = (Ontology) oDao.getOntologyByURI(p.getNamespace()); if (o == null) { if (!VitroVocabulary.vitroURI.equals(p.getNamespace())) { log.debug("doGet(): no ontology object found for the namespace " + p.getNamespace()); } } else { ontologyHash.put(p.getNamespace(), o.getName() == null ? p.getNamespace() : o.getName()); } } if (ontologyUri != null && p.getNamespace().equals(ontologyUri)) { scratch.add(p); } } } if (ontologyUri != null) { props = scratch; } if (props != null) { Collections.sort(props, new ObjectPropertyHierarchyListingController.ObjectPropertyAlphaComparator()); } ArrayList results = new ArrayList(); results.add("XX"); // column 1 results.add("property public name"); // column 2 results.add("prefix + local name"); // column 3 results.add("domain"); // column 4 results.add("range"); // column 5 results.add("group"); // column 6 results.add("display tier"); // column 7 results.add("display level"); // column 8 results.add("update level"); // column 9 if (props != null) { if (props.size() == 0) { results.add("XX"); results.add("<strong>" + noResultsMsgStr + "</strong>"); results.add(""); results.add(""); results.add(""); results.add(""); results.add(""); results.add(""); results.add(""); } else { Iterator propsIt = props.iterator(); while (propsIt.hasNext()) { ObjectProperty prop = (ObjectProperty) propsIt.next(); results.add("XX"); String propNameStr = ObjectPropertyHierarchyListingController.getDisplayLabel(prop); try { results.add("<a href=\"./propertyEdit?uri=" + URLEncoder.encode(prop.getURI(), "UTF-8") + "\">" + propNameStr + "</a>"); // column 1 } catch (Exception e) { results.add(propNameStr); // column 2 } results.add(prop.getLocalNameWithPrefix()); // column 3 VClass vc = (prop.getDomainVClassURI() != null) ? vcDao.getVClassByURI(prop.getDomainVClassURI()) : null; String domainStr = (vc != null) ? vc.getLocalNameWithPrefix() : ""; results.add(domainStr); // column 4 vc = (prop.getRangeVClassURI() != null) ? vcDao.getVClassByURI(prop.getRangeVClassURI()) : null; String rangeStr = (vc != null) ? vc.getLocalNameWithPrefix() : ""; results.add(rangeStr); // column 5 if (prop.getGroupURI() != null) { PropertyGroup pGroup = pgDao.getGroupByURI(prop.getGroupURI()); results.add(pGroup == null ? "unknown group" : pGroup.getName()); // column 6 } else { results.add("unspecified"); } if (prop.getDomainDisplayTierInteger() != null) { results.add(Integer.toString(prop.getDomainDisplayTierInteger(), BASE_10)); // column 7 } else { results.add(""); // column 7 } results.add(prop.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)" : prop.getHiddenFromDisplayBelowRoleLevel().getShorthand()); // column 8 results.add(prop.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)" : prop.getProhibitedFromUpdateBelowRoleLevel().getShorthand()); // column 9 } } request.setAttribute("results", results); } request.setAttribute("columncount", new Integer(NUM_COLS)); request.setAttribute("suppressquery", "true"); request.setAttribute("title", "Object Properties"); request.setAttribute("bodyJsp", Controllers.HORIZONTAL_JSP); // new way of adding more than one button List<ButtonForm> buttons = new ArrayList<ButtonForm>(); HashMap<String, String> newPropParams = new HashMap<String, String>(); newPropParams.put("controller", "Property"); ButtonForm newPropButton = new ButtonForm(Controllers.RETRY_URL, "buttonForm", "Add new object property", newPropParams); buttons.add(newPropButton); HashMap<String, String> rootPropParams = new HashMap<String, String>(); rootPropParams.put("iffRoot", "true"); String temp; if ((temp = vrequest.getParameter("ontologyUri")) != null) { rootPropParams.put("ontologyUri", temp); } ButtonForm rootPropButton = new ButtonForm("showObjectPropertyHierarchy", "buttonForm", "root properties", rootPropParams); buttons.add(rootPropButton); request.setAttribute("topButtons", buttons); /* original way of adding 1 button request.setAttribute("horizontalJspAddButtonUrl", Controllers.RETRY_URL); request.setAttribute("horizontalJspAddButtonText", "Add new object property"); request.setAttribute("horizontalJspAddButtonControllerParam", "Property"); */ RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); try { rd.forward(request, response); } catch (Throwable t) { t.printStackTrace(); } }
From source file:app.MainPanel.java
private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed String waluta = jComboBox2.getSelectedItem().toString(); HashMap temp = pozycje.get(waluta); jLabel10.setText(temp.get("kod_waluty").toString()); jLabel11.setText(temp.get("nazwa_waluty").toString()); jLabel12.setText(temp.get("przelicznik").toString()); if (temp.containsKey("kurs_sredni")) { jLabel9.setText("Kurs redni"); jLabel13.setText(temp.get("kurs_sredni").toString()); } else {// w w w. ja v a 2 s . c o m jLabel9.setText("Kurs kupna"); jLabel13.setText(temp.get("kurs_kupna").toString()); jLabel14.setText("Kurs sprzeday"); jLabel15.setText(temp.get("kurs_sprzedazy").toString()); } }
From source file:com.cloud.test.regression.ApiCommand.java
public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host, String parameters) {//from w w w . ja v a2s .c om boolean result = false; HashMap<String, Integer> actualEvents = new HashMap<String, Integer>(); try { // get actual events String url = host + "/?command=listEvents&" + parameters; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is, new String[] { "event" }); for (int i = 0; i < eventValues.size(); i++) { HashMap<String, String> element = eventValues.get(i); if (element.get("level").equals(level)) { if (actualEvents.containsKey(element.get("type")) == true) { actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1); } else { actualEvents.put(element.get("type"), 1); } } } } method.releaseConnection(); } catch (Exception ex) { s_logger.error(ex); } // compare actual events with expected events Iterator<?> iterator = expectedEvents.keySet().iterator(); Integer expected; Integer actual; int fail = 0; while (iterator.hasNext()) { expected = null; actual = null; String type = iterator.next().toString(); expected = expectedEvents.get(type); actual = actualEvents.get(type); if (actual == null) { s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected); fail++; } else if (expected.compareTo(actual) != 0) { fail++; s_logger.info("Amount of events of " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected + ", actual number is " + actual); } } if (fail == 0) { result = true; } return result; }
From source file:edu.umass.cs.gigapaxos.PaxosPacketBatcher.java
private boolean enqueueImpl(AcceptReplyPacket acceptReply) { if (!this.acceptReplies.containsKey(acceptReply.getPaxosID())) this.acceptReplies.put(acceptReply.getPaxosID(), new HashMap<Ballot, BatchedAcceptReply>()); HashMap<Ballot, BatchedAcceptReply> arMap = this.acceptReplies.get(acceptReply.getPaxosID()); boolean added = false; if (arMap.isEmpty()) added = (arMap.put(acceptReply.ballot, new BatchedAcceptReply(acceptReply)) != null); else if (arMap.containsKey(acceptReply.ballot)) { added = arMap.get(acceptReply.ballot).addAcceptReply(acceptReply); } else {/*from w w w . j a va 2s . c o m*/ arMap.put(acceptReply.ballot, new BatchedAcceptReply(acceptReply)); } return added; }
From source file:com.deafgoat.ml.prognosticator.Charter.java
/** * Creates data set containing categorical attributes along with prediction * confidence/*from w w w . j a v a2s . co m*/ * * @param files * List of files containing predictions to chart * @return the series collection to chart */ private DefaultCategoryDataset createCategoricalDataset(String[] files) { _logger.info("Collating data"); BufferedReader br = null; // final XYSeriesCollection dataset = new XYSeriesCollection(); final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); XYSeries prediction = null; for (String dataFile : files) { try { String sCurrentLine; prediction = new XYSeries(dataFile); br = new BufferedReader(new FileReader(dataFile)); HashMap<String, Double> avgConfidence = new HashMap<String, Double>(); HashMap<String, Integer> valueCount = new HashMap<String, Integer>(); while ((sCurrentLine = br.readLine()) != null) { String[] data = sCurrentLine.split("\t"); try { if (avgConfidence.containsKey(data[0])) { avgConfidence.put(data[0], avgConfidence.get(data[0]) + Double.parseDouble(data[1])); valueCount.put(data[0], valueCount.get(data[0]) + 1); } else { avgConfidence.put(data[0], Double.parseDouble(data[1])); valueCount.put(data[0], 1); } } catch (NumberFormatException e) { continue; } } for (Entry<String, Double> entry : avgConfidence.entrySet()) { dataset.addValue(entry.getValue() / valueCount.get(entry.getKey()), entry.getKey(), dataFile); } } catch (IOException e) { _logger.error(e.toString()); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { _logger.error(e.toString()); } } if (prediction != null) { // dataset.addSeries(prediction); } } return dataset; }
From source file:com.verisignlabs.dnssec.cl.ZoneFormat.java
private static void determineNSEC3Owners(List<Record> zone) throws NoSuchAlgorithmException { // Put the zone into a consistent (name and RR type) order. Collections.sort(zone, new RecordComparator()); // first, find the NSEC3PARAM record -- this is an inefficient linear // search, although it should be near the head of the list. NSEC3PARAMRecord nsec3param = null;/*ww w . j av a 2s. co m*/ HashMap<String, String> map = new HashMap<String, String>(); base32 b32 = new base32(base32.Alphabet.BASE32HEX, false, true); Name zonename = null; for (Record r : zone) { if (r.getType() == Type.SOA) { zonename = r.getName(); continue; } if (r.getType() == Type.NSEC3PARAM) { nsec3param = (NSEC3PARAMRecord) r; break; } } // If we couldn't determine a zone name, we have an issue. if (zonename == null) return; // If there wasn't one, we have nothing to do. if (nsec3param == null) return; // Next pass, calculate a mapping between ownernames and hashnames Name last_name = null; for (Record r : zone) { if (r.getName().equals(last_name)) continue; if (r.getType() == Type.NSEC3) continue; Name n = r.getName(); byte[] hash = nsec3param.hashName(n); String hashname = b32.toString(hash); map.put(hashname, n.toString().toLowerCase()); last_name = n; // inefficiently create hashes for the possible ancestor ENTs for (int i = zonename.labels() + 1; i < n.labels(); ++i) { Name parent = new Name(n, n.labels() - i); byte[] parent_hash = nsec3param.hashName(parent); String parent_hashname = b32.toString(parent_hash); if (!map.containsKey(parent_hashname)) { map.put(parent_hashname, parent.toString().toLowerCase()); } } } // Final pass, assign the names if we can for (ListIterator<Record> i = zone.listIterator(); i.hasNext();) { Record r = i.next(); if (r.getType() != Type.NSEC3) continue; NSEC3Record nsec3 = (NSEC3Record) r; String hashname = nsec3.getName().getLabelString(0).toLowerCase(); String ownername = (String) map.get(hashname); NSEC3Record new_nsec3 = new NSEC3Record(nsec3.getName(), nsec3.getDClass(), nsec3.getTTL(), nsec3.getHashAlgorithm(), nsec3.getFlags(), nsec3.getIterations(), nsec3.getSalt(), nsec3.getNext(), nsec3.getTypes(), ownername); i.set(new_nsec3); } }
From source file:infrascructure.data.vocabulary.SimpleVocabularyBuider.java
protected Collection<Word> retrieveWords(ResourceMetaData resource) { String wordPattern = WORD_PATTERN; Pattern pattern = Pattern.compile(wordPattern, Pattern.CASE_INSENSITIVE); String source = resource.getData(); Matcher matcher = pattern.matcher(source); HashMap<String, Word> wordsMap = new LinkedHashMap<>(200); while (matcher.find()) { String word = matcher.group().toLowerCase(); int indexOfAp = word.indexOf("'"); if (indexOfAp != -1) { String[] ww = word.split("'"); word = ww[0];/*from w ww. j a v a2 s . com*/ } if (!stopWords.contains(word)) { String stemmedWord = stemmer.getCanonicalForm(word); if (!stopWords.contains(stemmedWord) && word.length() > 2) { Set<String> originalWords = wordsMap.containsKey(stemmedWord) ? wordsMap.get(stemmedWord).getOriginalWords() : new HashSet<>(); originalWords.add(word); if (!wordsMap.containsKey(stemmedWord)) { wordsMap.put(stemmedWord, new Word(stemmedWord, 1, originalWords)); } else { Word existedToken = wordsMap.get(stemmedWord); wordsMap.put(stemmedWord, new Word(stemmedWord, existedToken.getCount() + 1, originalWords)); } } } } return wordsMap.values(); }
From source file:no.dusken.aranea.web.control.PageController.java
public ModelAndView handleArticle(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (showUnpublished) { //assuming that when this is true, we do not want caching. response.setHeader("Cache-Control", "no-cache"); } else {/* ww w . j av a 2 s .co m*/ response.setHeader("Cache-Control", "max-age=3600"); } Long ID; Page p; if (request.getParameter("externalID") != null) { ID = ServletRequestUtils.getRequiredLongParameter(request, "externalID"); p = pageService.getEntityByExternalID(ID); } else { ID = ServletRequestUtils.getLongParameter(request, "ID", 0); p = pageService.getEntity(ID); } Calendar now = new GregorianCalendar(); if (p == null || (p != null && !((p.getPublished() || showUnpublished) && p.getVisibleFrom().before(now) && now.before(p.getVisibleTo())))) { throw new PageNotFoundException("Page with ID: " + ID); } if (p instanceof Article) { Article article = (Article) p; List<String> paragraphs = getParagraphs(article); map.put("paragraphs", paragraphs); map.put("photographers", pageService.getPhotographers(article)); map.put("drawers", pageService.getDrawers(article)); int pages = 1; if (paragraphs.size() > MAX_PARAGRAPHS) { pages = paragraphs.size() / MAX_PARAGRAPHS; if (paragraphs.size() % MAX_PARAGRAPHS >= (MAX_PARAGRAPHS / 2)) { pages++; } } int articlePage = ServletRequestUtils.getIntParameter(request, "articlepage", 1); if (articlePage < 1 || articlePage > pages) { articlePage = 1; } int startIndex, endIndex; if (pages == 1) { startIndex = 1; endIndex = paragraphs.size(); } else { int paragraphs_per_page = paragraphs.size() / pages; startIndex = paragraphs_per_page * (articlePage - 1) + 1; endIndex = startIndex + paragraphs_per_page + 1; if (endIndex >= paragraphs.size()) { endIndex = paragraphs.size(); } } map.put("articleStartIndex", startIndex); map.put("articleEndIndex", endIndex); map.put("articlePage", articlePage); map.put("articlePageCount", pages); } map.put("article", p); HashMap<String, List<Page>> relationMap = new HashMap<String, List<Page>>(); HashMap<Integer, List<PageRelation>> paragraphRelationMap = new HashMap<Integer, List<PageRelation>>(); for (PageRelation pr : p.getPageRelations()) { Integer paragraph = pr.getParagraph(p); Page relatedPage = pr.getPageRelatedTo(p); if (paragraph == 0) { String description = pr.getDescription(p); if (relationMap.containsKey(description)) { relationMap.get(description).add(relatedPage); } else { List<Page> list = new LinkedList<Page>(); list.add(relatedPage); relationMap.put(description, list); } } else { if (paragraphRelationMap.containsKey(paragraph)) { paragraphRelationMap.get(paragraph).add(pr); } else { List<PageRelation> list = new LinkedList<PageRelation>(); list.add(pr); paragraphRelationMap.put(paragraph, list); } } } map.put("paragraphPagerelations", paragraphRelationMap); map.put("pageRelations", relationMap); map.put("captchaString", UUID.randomUUID().toString()); return new ModelAndView(ARTICLEVIEW, map); }