List of usage examples for java.util HashMap containsKey
public boolean containsKey(Object key)
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Converts a class to a SwaggerModel API representation and adds it to the models HashMap. Any property of the * class that is a @JsonProperty will be documented. @ApiModelProperty annotations are documented * and addModel will be called recursively with any properties which reference other classes that should be * documented as well. For instance, if Class1 has a property that is List[Class2], * then addModel will be called with Class2. * * @param models The hashmap of models that are being documented so that they can be referenced by swagger-ui. * @param model The model to add to the models hashmap. */// ww w. j a va2s. co m private void addModel(HashMap<String, SwaggerModel> models, Class<?> model) { String modelName = model.getSimpleName(); if (!models.containsKey(modelName)) { // TODO(lisbakke): Add @ApiModel description into our output once swagger-ui supports adding documentation for // an ApiModel. https://www.pivotaltracker.com/story/show/52998073 SwaggerModel swaggerModel = new SwaggerModel(); swaggerModel.setId(modelName); swaggerModel.setName(modelName); HashMap<String, SwaggerModelProperty> modelProperties = new HashMap<>(); Class<?> curClass = model; List<Field> declaredFields = new ArrayList<>(); // Get the properties from the class and its superclasses. while (curClass != null) { declaredFields.addAll(Arrays.asList(curClass.getDeclaredFields())); curClass = curClass.getSuperclass(); } int numProperties = 0; // For each property, get it's data and possibly recurse to addModel. for (Field property : declaredFields) { if (property.getAnnotation(JsonProperty.class) != null) { SwaggerModelProperty modelProperty = new SwaggerModelProperty(); String type = property.getType().getSimpleName(); modelProperty = handleCollectionType(property, models, modelProperty); modelProperty.setType(type); ApiModelProperty apiModelProperty = property.getAnnotation(ApiModelProperty.class); if (apiModelProperty != null) { modelProperty.setDescription(apiModelProperty.value()); modelProperty.setRequired(apiModelProperty.required()); String allowableValues = apiModelProperty.allowableValues(); if (allowableValues != null && !allowableValues.isEmpty()) { modelProperty .setAllowableValues(parseAllowableValues(apiModelProperty.allowableValues())); } } modelProperties.put(property.getName(), modelProperty); // Make sure this property of this class will also have a model built for it. addModel(models, property.getType()); numProperties++; } } if (numProperties > 0) { swaggerModel.setProperties(modelProperties); models.put(modelName, swaggerModel); } } }
From source file:com.krawler.spring.profileHandler.profileHandlerDAOImpl.java
public KwlReturnObject getUserDetails(HashMap<String, Object> requestParams, ArrayList filter_names, ArrayList filter_params) throws ServiceException { List ll = new ArrayList(); int dl = 0;/*from w w w .j av a 2 s . c o m*/ int start = 0; int limit = 0; String serverSearch = ""; try { if (requestParams.containsKey("start") && !StringUtil.isNullOrEmpty(requestParams.get("start").toString())) { start = Integer.parseInt(requestParams.get("start").toString()); } if (requestParams.containsKey("limit") && !StringUtil.isNullOrEmpty(requestParams.get("limit").toString())) { limit = Integer.parseInt(requestParams.get("limit").toString()); } if (requestParams.containsKey("ss") && !StringUtil.isNullOrEmpty(requestParams.get("ss").toString())) { serverSearch = requestParams.get("ss").toString(); } String SELECT_USER_INFO = "from User u "; String filterQuery = StringUtil.filterQuery(filter_names, "where"); SELECT_USER_INFO += filterQuery; if (requestParams.containsKey("email") && requestParams.get("email") != null) { SELECT_USER_INFO += " and emailID != '' "; } if (!StringUtil.isNullOrEmpty(serverSearch)) { String[] searchcol = new String[] { "u.firstName", "u.lastName" }; StringUtil.insertParamSearchString(filter_params, serverSearch, 2); String searchQuery = StringUtil.getSearchString(serverSearch, "and", searchcol); SELECT_USER_INFO += searchQuery; } if (requestParams.containsKey("usersList") && requestParams.get("usersList") != null) { StringBuffer usersList = (StringBuffer) requestParams.get("usersList"); SELECT_USER_INFO += " and u.userID in (" + usersList + ") order by firstName||' '||lastName "; } ll = executeQuery(SELECT_USER_INFO, filter_params.toArray()); dl = ll.size(); if (requestParams.containsKey("start") && !StringUtil.isNullOrEmpty(requestParams.get("start").toString()) && requestParams.containsKey("limit") && !StringUtil.isNullOrEmpty(requestParams.get("limit").toString())) { ll = executeQueryPaging(SELECT_USER_INFO, filter_params.toArray(), new Integer[] { start, limit }); } } catch (Exception e) { throw ServiceException.FAILURE("profileHandlerDAOImpl.getUserDetails", e); } return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl); }
From source file:com.sfs.whichdoctor.importer.ExamImporter.java
/** * Assign data./*w w w.java2s .c o m*/ * * @param personDAO the person dao * * @return the hash map< object, list< object>> * * @throws WhichDoctorImporterException the which doctor importer exception */ protected final HashMap<Object, List<Object>> assignData(final PersonDAO personDAO) throws WhichDoctorImporterException { importLogger.debug("Getting data map"); HashMap<String, List<String>> dataMap = this.getDataMap(); if (dataMap == null) { throw new WhichDoctorImporterException("Error importing " + "- the data map cannot be null"); } List<Integer> indexValues = new ArrayList<Integer>(); TreeMap<Integer, PersonBean> keyMap = new TreeMap<Integer, PersonBean>(); // Load the index values if (dataMap.containsKey("MIN") || dataMap.containsKey("Candidate No.")) { importLogger.debug("Datamap contains index key"); // The submitted data has a key field, load associated people if (dataMap.containsKey("MIN")) { // Load person based on MIN for (String strIdentifier : dataMap.get("MIN")) { try { Integer identifier = new Integer(strIdentifier); if (!keyMap.containsKey(identifier)) { PersonBean person = personDAO.loadIdentifier(identifier, new BuilderBean()); if (person != null) { keyMap.put(identifier, person); } } indexValues.add(identifier); } catch (Exception e) { setImportMessage("Error loading person with MIN: " + strIdentifier); importLogger.error("Error loading person with MIN: " + e.getMessage()); } } } else { // dataMap has Candidate number but not MIN for (String strCandidateNo : dataMap.get("Candidate No.")) { try { Integer candidateNo = new Integer(strCandidateNo); if (!keyMap.containsKey(candidateNo)) { PersonBean person = personDAO.loadCandidateNumber(candidateNo.intValue(), new BuilderBean()); if (person != null) { keyMap.put(candidateNo, person); } } indexValues.add(candidateNo); } catch (Exception e) { setImportMessage("Error loading person with Candidate " + "Number: " + strCandidateNo); importLogger.error("Error loading person with " + "Candidate Number: " + e.getMessage()); } } } } // With the index values loaded cycle through and create the actual // beans for (int i = 0; i < indexValues.size(); i++) { Integer index = (Integer) indexValues.get(i); if (keyMap.containsKey(index)) { PersonBean person = (PersonBean) keyMap.get(index); if (person == null) { throw new WhichDoctorImporterException("Person is null"); } try { // Set the values of the exam object ExamBean exam = new ExamBean(); exam.setReferenceGUID(person.getGUID()); exam.setLogMessage("Created via automated import process"); if (dataMap.containsKey("Exam Type")) { List<String> values = dataMap.get("Exam Type"); importLogger.info("Exam Type: " + values.get(i)); exam.setType(values.get(i)); } if (dataMap.containsKey("Exam Date")) { List<String> values = dataMap.get("Exam Date"); importLogger.info("Exam Date: " + DataFilter.parseDate(values.get(i), true)); exam.setDateSat(DataFilter.parseDate(values.get(i), true)); } if (dataMap.containsKey("Exam Venue")) { List<String> values = dataMap.get("Exam Venue"); importLogger.info("Exam Venue: " + values.get(i)); exam.setLocation(values.get(i)); } if (dataMap.containsKey("Result")) { List<String> values = dataMap.get("Result"); importLogger.info("Result: " + values.get(i)); String status = checkInput("Result", values.get(i)); exam.setStatus(status); } if (dataMap.containsKey("Result Band")) { List<String> values = dataMap.get("Result Band"); importLogger.info("Result Band: " + values.get(i)); exam.setStatusLevel(values.get(i)); } setBeanArray(person, exam); } catch (Exception e) { setImportMessage("Error setting values for exam associated to: " + OutputFormatter.toFormattedName(person)); importLogger.error("Error setting values for exam: " + e.getMessage()); } } } return this.getBeanMap(); }
From source file:eu.sisob.uma.NPL.Researchers.GateResearcherAnnCollector_Deprecated.java
/** * * @param doc/*from ww w . j a v a 2s .co m*/ * @param aoData */ @Override public void collect(Object doc, MiddleData aoData) { int n_expressions = 0; org.dom4j.Element eOut = org.dom4j.DocumentFactory.getInstance().createElement("blockinfo"); eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ANNOTATIONRECOLLECTING, aoData.getId_annotationrecollecting()); // aoData[MiddleData.I_INDEX_DATA_TYPE].toString()); eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ENTITY_ATT, aoData.getId_entity()); // aoData[MiddleData.I_INDEX_DATA_ID].toString()); gate.Document docGate = (gate.Document) doc; HashMap<String, String> extra_data = null; try { extra_data = (HashMap<String, String>) aoData.getData_extra(); } catch (Exception ex) { extra_data = null; } boolean collect_expressions = true; if (extra_data != null) { if (extra_data.containsKey(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE)) { String block_type = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_BLOCK_TYPE); if (block_type.equals(CVBlocks.CVBLOCK_OTHERS)) { collect_expressions = false; } } else { } } eOut.addAttribute("URL", docGate.getSourceUrl() != null ? docGate.getSourceUrl().toString() : ""); if (collect_expressions) { AnnotationSet annoset = docGate.getAnnotations(); List<Annotation> anns = new ArrayList<Annotation>(); //Expressions anns.addAll(annoset.get("ProfessionalActivityCurrent")); anns.addAll(annoset.get("ProfessionalActivityNoCurrent")); anns.addAll(annoset.get("AccreditedUniversityStudiesOtherPostGrade")); anns.addAll(annoset.get("AccreditedUniversityStudiesDegree")); anns.addAll(annoset.get("AccreditedUniversityStudiesPhDStudies")); //Collections.sort(anns, new OffsetBeginEndComparator()); //need to bee order if (anns.size() > 0) { for (Annotation an : anns) { String cvnItemName = an.getType(); org.dom4j.Element eAux = new org.dom4j.DocumentFactory().createElement(cvnItemName); // eAux.addElement("Domain").addText(gate.Utils.stringFor(docGate, // an.getStartNode().getOffset() > 100 ? an.getStartNode().getOffset() - 100 : an.getStartNode().getOffset(), // an.getEndNode().getOffset() + 100 < docGate.getContent().size() ? an.getEndNode().getOffset() + 100 : an.getEndNode().getOffset())); eAux.addAttribute("action_mode", "add"); eAux.addElement("Content").addText(gate.Utils.stringFor(docGate, an)); FeatureMap fmap = an.getFeatures(); for (Object key : fmap.keySet()) { String fieldName = key.toString(); eAux.addElement(fieldName).addText(fmap.get(key).toString()); } eOut.add(eAux); } } n_expressions += eOut.elements().size(); anns = new ArrayList<Annotation>(); anns.addAll(annoset.get("AgentIdentification")); if (anns.size() > 0) { String lastname = ""; String initials = ""; String name = ""; String firstname = ""; if (extra_data != null) { lastname = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_LASTNAME); initials = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_INITIALS); name = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_NAME); firstname = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_FIRSTNAME); } if (firstname.equals("")) { firstname = initials; } for (Annotation an : anns) { String cvnItemName = an.getType(); org.dom4j.Element eAux = new org.dom4j.DocumentFactory().createElement(cvnItemName); // eAux.addElement("Domain").addText(gate.Utils.stringFor(docGate, // an.getStartNode().getOffset() > 100 ? an.getStartNode().getOffset() - 100 : an.getStartNode().getOffset(), // an.getEndNode().getOffset() + 100 < docGate.getContent().size() ? an.getEndNode().getOffset() + 100 : an.getEndNode().getOffset())); eAux.addAttribute("action_mode", "overwrite"); eAux.addAttribute("extra_gets", "getInformation"); eAux.addElement("Content").addText(gate.Utils.stringFor(docGate, an)); FeatureMap fmap = an.getFeatures(); for (Object key : fmap.keySet()) { String fieldName = key.toString(); eAux.addElement(fieldName).addText(fmap.get(key).toString()); } eAux.addElement(CVItemExtracted.AgentIdentification.GivenName).addText(firstname); eAux.addElement(CVItemExtracted.AgentIdentification.FirstFamilyName).addText(lastname); eOut.add(eAux); } } n_expressions += eOut.elements().size(); ProjectLogger.LOGGER .info(String.format("%3d expressions in %s : ", n_expressions, docGate.getSourceUrl())); // + docXML.asXML() if (eOut == null) ProjectLogger.LOGGER.info("Output is null"); // + docXML.asXML() aoData.setData_out(eOut); } if (aoData.getVerbose()) { File dest_dir = aoData.getVerboseDir(); File path = null; String fileName = ""; if (extra_data != null && extra_data.containsKey(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_DOCUMENT_NAME)) { fileName = extra_data.get(DataExchangeLiterals.MIDDLE_ELEMENT_XML_EXTRADATA_DOCUMENT_NAME); } else { URL url = docGate.getSourceUrl(); try { path = new File(url.toURI()); fileName = path.getName(); } catch (Exception e) { String filename; try { filename = URLEncoder.encode(url.toString(), "UTF-8") + ".html"; } catch (Exception ex) { filename = docGate.getName() + ".html"; } path = new File(filename); fileName = path.getName(); } if (!fileName.equals("")) { fileName = fileName.substring(0, fileName.lastIndexOf(".")); } } File file_result = new File(dest_dir, fileName + "_verbose.html"); try { writeResultsInHTMLFile(docGate, file_result); } catch (Exception ex) { Logger.getRootLogger().error("Error writing verbose results. " + ex.toString()); } } }
From source file:com.parse.ParseAddUniqueOperation.java
@Override public Object apply(Object oldValue, String key) { if (oldValue == null) { return new ArrayList<>(objects); } else if (oldValue instanceof JSONArray) { ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue); @SuppressWarnings("unchecked") ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key); return new JSONArray(newValue); } else if (oldValue instanceof List) { ArrayList<Object> result = new ArrayList<>((List<?>) oldValue); // Build up a Map of objectIds of the existing ParseObjects in this field. HashMap<String, Integer> existingObjectIds = new HashMap<>(); for (int i = 0; i < result.size(); i++) { if (result.get(i) instanceof ParseObject) { existingObjectIds.put(((ParseObject) result.get(i)).getObjectId(), i); }// w w w . jav a 2s . c o m } // Iterate over the objects to add. If it already exists in the field, // remove the old one and add the new one. Otherwise, just add normally. for (Object obj : objects) { if (obj instanceof ParseObject) { String objectId = ((ParseObject) obj).getObjectId(); if (objectId != null && existingObjectIds.containsKey(objectId)) { result.set(existingObjectIds.get(objectId), obj); } else if (!result.contains(obj)) { result.add(obj); } } else { if (!result.contains(obj)) { result.add(obj); } } } return result; } else { throw new IllegalArgumentException("Operation is invalid after previous operation."); } }
From source file:com.sonicle.webtop.contacts.io.input.ContactExcelFileReader.java
protected void readRow(HashMap<String, Integer> columnIndexes, BeanHandler beanHandler, int row, RowValues rowBean) throws Exception { LogEntries log = new LogEntries(); Contact contact = null;/*from w w w . j a va 2s.c o m*/ try { LogEntries ilog = new LogEntries(); contact = new Contact(); for (FileRowsReader.FieldMapping mapping : mappings) { if (StringUtils.isBlank(mapping.source)) continue; if (!columnIndexes.containsKey(mapping.source)) throw new Exception("Index not found"); Integer index = columnIndexes.get(mapping.source); fillContactByMapping(contact, mapping.target, rowBean.get(index)); } if (contact.trimFieldLengths()) { ilog.add(new MessageLogEntry(LogEntry.Level.WARN, "Some fields were truncated due to max-length")); } if (!ilog.isEmpty()) { log.addMaster(new MessageLogEntry(LogEntry.Level.WARN, "ROW [{0}]", row + 1)); log.addAll(ilog); } } catch (Throwable t) { log.addMaster( new MessageLogEntry(LogEntry.Level.ERROR, "ROW [{0}]. Reason: {1}", row + 1, t.getMessage())); } finally { boolean ret = beanHandler.handle(new ContactInput(contact), log); if (!ret) throw new Exception("Handle not succesful"); } }
From source file:org.apache.lens.regression.util.Util.java
public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception { Path p = Paths.get(remotePath); String fileName = p.getFileName().toString(); backupFile = localFilePath + "backup-" + fileName; localFile = localFilePath + fileName; log.info("Copying " + remotePath + " to " + localFile); remoteFile("get", remotePath, localFile); Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(new FileInputStream(localFile)); doc.normalize();/*from www . ja v a 2s. c om*/ NodeList rootNodes = doc.getElementsByTagName("configuration"); Node root = rootNodes.item(0); Element rootElement = (Element) root; NodeList property = rootElement.getElementsByTagName("property"); for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document Node prop = property.item(i); Element propElement = (Element) prop; Node propChild = propElement.getElementsByTagName("name").item(0); Element nameElement = (Element) propChild; if (map.containsKey(nameElement.getTextContent())) { rootElement.removeChild(prop); i--; } } Iterator<Entry<String, String>> ab = map.entrySet().iterator(); while (ab.hasNext()) { Entry<String, String> entry = ab.next(); String propertyName = entry.getKey(); String propertyValue = entry.getValue(); System.out.println(propertyName + " " + propertyValue + "\n"); Node newNode = doc.createElement("property"); rootElement.appendChild(newNode); Node newName = doc.createElement("name"); Element newNodeElement = (Element) newNode; newName.setTextContent(propertyName); newNodeElement.appendChild(newName); Node newValue = doc.createElement("value"); newValue.setTextContent(propertyValue); newNodeElement.appendChild(newValue); } prettyPrint(doc); remoteFile("put", remotePath, localFile); }
From source file:com.transage.privatespace.vcard.pim.vcard.VCardComposer.java
/** Loop append TEL property. */ private void appendPhoneStr(List<PhoneData> phoneList, int version) { HashMap<String, String> numMap = new HashMap<String, String>(); String joinMark = version == VERSION_VCARD21_INT ? ";" : ","; for (PhoneData phone : phoneList) { String type;/* w w w .j av a 2 s. c o m*/ if (!isNull(phone.data)) { type = getPhoneTypeStr(phone); if (version == VERSION_VCARD30_INT && type.indexOf(";") != -1) { type = type.replace(";", ","); } if (numMap.containsKey(phone.data)) { type = numMap.get(phone.data) + joinMark + type; } numMap.put(phone.data, type); } } for (Map.Entry<String, String> num : numMap.entrySet()) { if (version == VERSION_VCARD21_INT) { mResult.append("TEL;"); } else { // vcard3.0 mResult.append("TEL;TYPE="); } mResult.append(num.getValue()).append(":").append(num.getKey()).append(mNewline); } }
From source file:my.home.model.datasource.AutoCompleteItemDataSourceImpl.java
private void setItemWeight(Context context, ArrayList<AutoCompleteItem> items, String from) { List<HistoryItem> historyItems = DBStaticManager.getLatestItems(context, from, HISTORY_ITEM_MAX_NUM); if (historyItems == null || historyItems.size() == 0) { Log.d(TAG, "no history from: " + from + ". Use default value."); return;//from w w w . ja v a 2s . c om } int hLen = historyItems.size(); /* TODO move to Util class */ HashMap<String, Integer> counter = new HashMap<>(hLen); for (HistoryItem item : historyItems) { String key = item.getFrom() + item.getTo(); if (counter.containsKey(key)) { counter.put(key, counter.get(key) + 1); } else { counter.put(key, 1); } } String lastValue = ""; float lastWeight = 0.0f; HashMap<String, Float> resultMap = new HashMap<>(); for (int i = 0; i < hLen; i++) { HistoryItem cItem = historyItems.get(i); String key = cItem.getFrom() + cItem.getTo(); // pos weight float pos_w = (i + 1) * 1.0f / hLen; pos_w = pos_w * pos_w; // occ weight float occ_w = counter.get(key) * 1.0f / hLen; // ctu weight float ctu_w = 0.0f; if (lastValue.equals(key)) { ctu_w = lastWeight / 2; } lastWeight = pos_w + occ_w + ctu_w; lastValue = key; if (resultMap.containsKey(key)) { resultMap.put(key, resultMap.get(key) + lastWeight); } else { resultMap.put(key, lastWeight); } } if (resultMap.size() != 0) { for (AutoCompleteItem item : items) { if (resultMap.containsKey(from + item.getContent())) { Log.d(TAG, "item:" + item.getContent() + " | " + resultMap.get(from + item.getContent())); item.setWeight(resultMap.get(from + item.getContent())); } } } }
From source file:org.archone.ad.rpc.RpcServiceImpl.java
public HashMap<String, Object> process(HttpSession session, HashMap<String, Object> request) throws SecurityViolationException, IllegalArgumentException, InvocationTargetException, IllegalAccessException {/* w w w . j a v a2 s. c om*/ HashMap rpcCall = this.callMap.get((String) request.get("rpcAction")); Assert.notNull(rpcCall, "Action not found"); try { String[] requiredFields = (String[]) rpcCall.get("required"); for (String field : requiredFields) { String[] fieldReqParts = field.split(":"); String fieldName = fieldReqParts[0]; if (!request.containsKey(fieldName)) { throw new MalformedRequestException("Field " + field + " required for this request"); } } Method method = (Method) rpcCall.get("method"); /* * Performing security checks if method is annotated with SecuredMethod */ if (method.isAnnotationPresent(SecuredMethod.class)) { String[] constraints = method.getAnnotation(SecuredMethod.class).constraints(); for (String constraint : constraints) { HashMap<String, Object> scUnit = scMap.get(constraint); if (scUnit != null) { Method scMethod = (Method) scUnit.get("method"); scMethod.invoke(scUnit.get("object"), new OperationContext(session, request)); } else { throw new RuntimeException("Failed to find a required security constraint"); } } } return (HashMap<String, Object>) method.invoke(rpcCall.get("object"), new OperationContext(session, request)); } catch (RuntimeException ex) { if (true) { throw ex; } Logger.getLogger(this.getClass().getName()).log(Level.INFO, ex.getMessage()); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", false); if (ex instanceof MalformedRequestException) { response.put("errors", new String[] { ex.getMessage() }); } else if (ex instanceof SecurityViolationException) { response.put("errors", new String[] { "Access Denied" }); } else { response.put("errors", new String[] { "Unknown Error" }); } return response; } }