Example usage for java.util HashMap putAll

List of usage examples for java.util HashMap putAll

Introduction

In this page you can find the example usage for java.util HashMap putAll.

Prototype

public void putAll(Map<? extends K, ? extends V> m) 

Source Link

Document

Copies all of the mappings from the specified map to this map.

Usage

From source file:oscar.oscarDemographic.pageUtil.DiabetesExportAction.java

void setDemographicDetails(PatientRecord patientRec, String demoNo) {
    Demographics demo = patientRec.addNewDemographics();
    org.oscarehr.common.model.Demographic demographic = new DemographicData().getDemographic(demoNo);

    cdsDt.PersonNameStandard.LegalName legalName = demo.addNewNames().addNewLegalName();
    cdsDt.PersonNameStandard.LegalName.FirstName firstName = legalName.addNewFirstName();
    cdsDt.PersonNameStandard.LegalName.LastName lastName = legalName.addNewLastName();
    legalName.setNamePurpose(cdsDt.PersonNamePurposeCode.L);

    String data = StringUtils.noNull(demographic.getFirstName());
    firstName.setPart(data);/*  w ww  .  j  a v a 2  s .c  o  m*/
    firstName.setPartType(cdsDt.PersonNamePartTypeCode.GIV);
    firstName.setPartQualifier(cdsDt.PersonNamePartQualifierCode.BR);
    if (StringUtils.empty(data)) {
        errors.add("Error! No First Name for Patient " + demoNo);
    }
    data = StringUtils.noNull(demographic.getLastName());
    lastName.setPart(data);
    lastName.setPartType(cdsDt.PersonNamePartTypeCode.FAMC);
    lastName.setPartQualifier(cdsDt.PersonNamePartQualifierCode.BR);
    if (StringUtils.empty(data)) {
        errors.add("Error! No Last Name for Patient " + demoNo);
    }

    data = StringUtils.noNull(demographic.getSex());
    demo.setGender(cdsDt.Gender.Enum.forString(data));
    if (StringUtils.empty(data)) {
        errors.add("Error! No Gender for Patient " + demoNo);
    }

    data = demographic.getProviderNo();
    demo.setOHIPPhysicianId("");
    if (StringUtils.filled(data)) {
        ProviderData provider = new ProviderData(data);

        data = StringUtils.noNull(provider.getOhip_no());
        if (data.length() <= 6)
            demo.setOHIPPhysicianId(data);
        else
            errors.add("Error! No OHIP Physician ID for Patient " + demoNo);

        data = provider.getPractitionerNo();
        if (data != null && data.length() == 5)
            demo.setPrimaryPhysicianCPSO(data);
    }

    data = StringUtils.noNull(demographic.getHin());
    cdsDt.HealthCard healthCard = demo.addNewHealthCard();
    healthCard.setNumber(data);
    if (StringUtils.empty(data))
        errors.add("Error! No Health Card Number for Patient " + demoNo);
    if (Util.setProvinceCode(demographic.getProvince()) != null)
        healthCard.setProvinceCode(Util.setProvinceCode(demographic.getProvince()));
    else
        healthCard.setProvinceCode(cdsDt.HealthCardProvinceCode.X_70); //Asked, unknown
    if (healthCard.getProvinceCode() == null) {
        errors.add("Error! No Health Card Province Code for Patient " + demoNo);
    }
    if (StringUtils.filled(demographic.getVer()))
        healthCard.setVersion(demographic.getVer());
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
    if (demographic.getHcRenewDate() != null)
        data = formatter.format(demographic.getHcRenewDate());
    else
        data = null;
    if (UtilDateUtilities.StringToDate(data) != null) {
        healthCard.setExpirydate(Util.calDate(data));
    }

    data = StringUtils.noNull(DemographicData.getDob(demographic, "-"));
    if (UtilDateUtilities.StringToDate(data) != null) {
        demo.addNewDateOfBirth().setFullDate(Util.calDate(data));
    }

    if (StringUtils.filled(demographic.getAddress())) {
        cdsDt.Address addr = demo.addNewAddress();
        cdsDt.AddressStructured address = addr.addNewStructured();
        addr.setAddressType(cdsDt.AddressType.R);
        address.setLine1(demographic.getAddress());
        if (StringUtils.filled(demographic.getCity()) || StringUtils.filled(demographic.getProvince())
                || StringUtils.filled(demographic.getPostal())) {
            address.setCity(StringUtils.noNull(demographic.getCity()));
            address.setCountrySubdivisionCode(Util.setCountrySubDivCode(demographic.getProvince()));
            address.addNewPostalZipCode()
                    .setPostalCode(StringUtils.noNull(demographic.getPostal()).replace(" ", ""));
        }
    }

    data = demographic.getEmail();
    if (StringUtils.filled(data))
        demo.setEmail(data);

    HashMap<String, String> demoExt = new HashMap<String, String>();
    demoExt.putAll(demographicExtDao.getAllValuesForDemo(demoNo));

    String phoneNo = Util.onlyNum(demographic.getPhone());
    if (StringUtils.filled(phoneNo) && phoneNo.length() >= 7) {
        cdsDt.PhoneNumber phoneResident = demo.addNewPhoneNumber();
        phoneResident.setPhoneNumberType(cdsDt.PhoneNumberType.R);
        phoneResident.setPhoneNumber(phoneNo);
        data = demoExt.get("hPhoneExt");
        if (data != null) {
            if (data.length() > 5) {
                data = data.substring(0, 5);
                errors.add("Home phone extension too long - trimmed for Patient " + demoNo);
            }
            phoneResident.setExtension(data);
        }
    }
}

From source file:org.kuali.rice.kim.impl.identity.PersonServiceImpl.java

public Map<String, String> convertPersonPropertiesToEntityProperties(Map<String, String> criteria) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("convertPersonPropertiesToEntityProperties: " + criteria);
    }/*from   w  w w  . j av  a2 s .  c  om*/
    boolean nameCriteria = false;
    boolean addressCriteria = false;
    boolean externalIdentifierCriteria = false;
    boolean affiliationCriteria = false;
    boolean affiliationDefaultOnlyCriteria = false;
    boolean phoneCriteria = false;
    boolean emailCriteria = false;
    boolean employeeIdCriteria = false;
    // add base lookups for all person lookups
    HashMap<String, String> newCriteria = new HashMap<String, String>();
    newCriteria.putAll(baseLookupCriteria);

    newCriteria.put("entityTypeContactInfos.entityTypeCode", personEntityTypeLookupCriteria);

    if (criteria != null) {
        for (String key : criteria.keySet()) {
            //check active radio button
            if (key.equals(KIMPropertyConstants.Person.ACTIVE)) {
                newCriteria.put(criteriaConversion.get(KIMPropertyConstants.Person.ACTIVE),
                        criteria.get(KIMPropertyConstants.Person.ACTIVE));
            } else {
                // The following if statement enables the "both" button to work correctly.
                if (!(criteria.containsKey(KIMPropertyConstants.Person.ACTIVE))) {
                    newCriteria.remove(KIMPropertyConstants.Person.ACTIVE);
                }
            }

            // if no value was passed, skip the entry in the Map
            if (StringUtils.isEmpty(criteria.get(key))) {
                continue;
            }
            // check if the value needs to be encrypted
            // handle encrypted external identifiers
            if (key.equals(KIMPropertyConstants.Person.EXTERNAL_ID)
                    && StringUtils.isNotBlank(criteria.get(key))) {
                // look for a ext ID type property
                if (criteria.containsKey(KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE)) {
                    String extIdTypeCode = criteria
                            .get(KIMPropertyConstants.Person.EXTERNAL_IDENTIFIER_TYPE_CODE);
                    if (StringUtils.isNotBlank(extIdTypeCode)) {
                        // if found, load that external ID Type via service
                        EntityExternalIdentifierType extIdType = getIdentityService()
                                .getExternalIdentifierType(extIdTypeCode);
                        // if that type needs to be encrypted, encrypt the value in the criteria map
                        if (extIdType != null && extIdType.isEncryptionRequired()) {
                            try {
                                if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
                                    criteria.put(key, CoreApiServiceLocator.getEncryptionService()
                                            .encrypt(criteria.get(key)));
                                }
                            } catch (GeneralSecurityException ex) {
                                LOG.error("Unable to encrypt value for external ID search of type "
                                        + extIdTypeCode, ex);
                            }
                        }
                    }
                }
            }

            // convert the property to the Entity data model
            String entityProperty = criteriaConversion.get(key);
            if (entityProperty != null) {
                newCriteria.put(entityProperty, criteria.get(key));
            } else {
                entityProperty = key;
                // just pass it through if no translation present
                newCriteria.put(key, criteria.get(key));
            }
            // check if additional criteria are needed based on the types of properties specified
            if (isNameEntityCriteria(entityProperty)) {
                nameCriteria = true;
            }
            if (isExternalIdentifierEntityCriteria(entityProperty)) {
                externalIdentifierCriteria = true;
            }
            if (isAffiliationEntityCriteria(entityProperty)) {
                affiliationCriteria = true;
            }
            if (isAddressEntityCriteria(entityProperty)) {
                addressCriteria = true;
            }
            if (isPhoneEntityCriteria(entityProperty)) {
                phoneCriteria = true;
            }
            if (isEmailEntityCriteria(entityProperty)) {
                emailCriteria = true;
            }
            if (isEmployeeIdEntityCriteria(entityProperty)) {
                employeeIdCriteria = true;
            }
            // special handling for the campus code, since that forces the query to look
            // at the default affiliation record only
            if (key.equals("campusCode")) {
                affiliationDefaultOnlyCriteria = true;
            }
        }

        if (nameCriteria) {
            newCriteria.put(ENTITY_NAME_PROPERTY_PREFIX + "active", "Y");
            newCriteria.put(ENTITY_NAME_PROPERTY_PREFIX + "defaultValue", "Y");
            //newCriteria.put(ENTITY_NAME_PROPERTY_PREFIX + "nameCode", "PRFR");//so we only display 1 result
        }
        if (addressCriteria) {
            newCriteria.put(ENTITY_ADDRESS_PROPERTY_PREFIX + "active", "Y");
            newCriteria.put(ENTITY_ADDRESS_PROPERTY_PREFIX + "defaultValue", "Y");
        }
        if (phoneCriteria) {
            newCriteria.put(ENTITY_PHONE_PROPERTY_PREFIX + "active", "Y");
            newCriteria.put(ENTITY_PHONE_PROPERTY_PREFIX + "defaultValue", "Y");
        }
        if (emailCriteria) {
            newCriteria.put(ENTITY_EMAIL_PROPERTY_PREFIX + "active", "Y");
            newCriteria.put(ENTITY_EMAIL_PROPERTY_PREFIX + "defaultValue", "Y");
        }
        if (employeeIdCriteria) {
            newCriteria.put(ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX + "active", "Y");
            newCriteria.put(ENTITY_EMPLOYEE_ID_PROPERTY_PREFIX + "primary", "Y");
        }
        if (affiliationCriteria) {
            newCriteria.put(ENTITY_AFFILIATION_PROPERTY_PREFIX + "active", "Y");
        }
        if (affiliationDefaultOnlyCriteria) {
            newCriteria.put(ENTITY_AFFILIATION_PROPERTY_PREFIX + "defaultValue", "Y");
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Converted: " + newCriteria);
    }
    return newCriteria;
}

From source file:com.healthcit.cacure.businessdelegates.FormManager.java

@Transactional
public BaseForm importFormToModule(final BaseModule module, final BaseForm form,
        boolean importToQuestionLibrary, HashMap<String, String> oldAnswerValueIdsNewAnswerValueIdsMap) {
    BaseForm newForm = module.newForm();
    newForm.setName(form.getName());//from w  w w  .ja v  a2 s .  c  om
    this.addNewForm(newForm);
    Map<String, String> _oldAnswerValueIdsNewAnswerValueIdsMap = importQuestionsToForms(form, newForm,
            importToQuestionLibrary, true);

    if (oldAnswerValueIdsNewAnswerValueIdsMap != null) {
        oldAnswerValueIdsNewAnswerValueIdsMap.putAll(_oldAnswerValueIdsNewAnswerValueIdsMap);
    }

    if (module instanceof Module && form instanceof FormLibraryForm) {
        formDao.updateFormLibraryForm((QuestionnaireForm) newForm, (FormLibraryForm) form);
    } else if (module instanceof FormLibraryModule && form instanceof QuestionnaireForm) {
        formDao.updateFormLibraryForm((QuestionnaireForm) form, (FormLibraryForm) newForm);
    }
    return newForm;
}

From source file:oscar.oscarDemographic.pageUtil.DiabetesExportAction.java

void setLaboratoryResults(PatientRecord patientRecord, String demoNo) throws SQLException {
    List<LabMeasurements> labMeaList = ImportExportMeasurements.getLabMeasurements(demoNo);
    for (LabMeasurements labMea : labMeaList) {
        String data = StringUtils.noNull(labMea.getExtVal("identifier"));
        String loinc = new MeasurementMapConfig().getLoincCodeByIdentCode(data);
        if (StringUtils.filled(loinc)) {
            loinc = loinc.trim();/*from w w  w  . jav a 2  s. c  o m*/
            if (loinc.equals("9318-7"))
                loinc = "14959-1"; //Urine Albumin-Creatinine Ratio
        }

        LaboratoryResults.TestName.Enum testName = LaboratoryResults.TestName.Enum.forString(loinc);
        if (testName == null)
            continue;

        LaboratoryResults labResults = patientRecord.addNewLaboratoryResults();
        labResults.setTestName(testName); //LOINC code
        labResults.setLabTestCode(data);

        cdsDt.DateFullOrPartial collDate = labResults.addNewCollectionDateTime();
        String sDateTime = labMea.getExtVal("datetime");
        if (StringUtils.filled(sDateTime)) {
            collDate.setFullDate(Util.calDate(sDateTime));
        } else {
            errors.add("Error! No Collection Datetime for Lab Test " + testName + " for Patient " + demoNo);
            collDate.setFullDate(Util.calDate("0001-01-01"));
        }

        data = labMea.getMeasure().getDataField();
        LaboratoryResults.Result result = labResults.addNewResult();
        if (StringUtils.filled(data)) {
            result.setValue(data);
        } else {
            errors.add("Error! No Result Value for Lab Test " + testName + " for Patient " + demoNo);
        }

        data = labMea.getExtVal("unit");
        if (StringUtils.filled(data)) {
            result.setUnitOfMeasure(data);
        } else {
            errors.add("Error! No Unit for Lab Test " + testName + " for Patient " + demoNo);
        }

        labResults.setLaboratoryName(StringUtils.noNull(labMea.getExtVal("labname")));
        if (StringUtils.empty(labResults.getLaboratoryName())) {
            errors.add("Error! No Laboratory Name for Lab Test " + testName + " for Patient " + demoNo);
        }

        labResults.setResultNormalAbnormalFlag(cdsDt.ResultNormalAbnormalFlag.U);
        data = StringUtils.noNull(labMea.getExtVal("abnormal"));
        if (data.equals("A") || data.equals("L"))
            labResults.setResultNormalAbnormalFlag(cdsDt.ResultNormalAbnormalFlag.Y);
        if (data.equals("N"))
            labResults.setResultNormalAbnormalFlag(cdsDt.ResultNormalAbnormalFlag.N);

        data = labMea.getExtVal("accession");
        if (StringUtils.filled(data)) {
            labResults.setAccessionNumber(data);
        }

        data = labMea.getExtVal("name");
        if (StringUtils.filled(data)) {
            labResults.setTestNameReportedByLab(data);
        }

        data = labMea.getExtVal("comments");
        if (StringUtils.filled(data)) {
            labResults.setNotesFromLab(Util.replaceTags(data));
        }

        String range = labMea.getExtVal("range");
        String min = labMea.getExtVal("minimum");
        String max = labMea.getExtVal("maximum");
        LaboratoryResults.ReferenceRange refRange = labResults.addNewReferenceRange();
        if (StringUtils.filled(range))
            refRange.setReferenceRangeText(range);
        else {
            if (StringUtils.filled(min))
                refRange.setLowLimit(min);
            if (StringUtils.filled(max))
                refRange.setHighLimit(max);
        }

        String reqDate = labMea.getExtVal("request_datetime");
        if (StringUtils.filled(reqDate))
            labResults.addNewLabRequisitionDateTime().setFullDate(Util.calDate(reqDate));

        String lab_no = labMea.getExtVal("lab_no");
        if (StringUtils.empty(lab_no))
            lab_no = labMea.getExtVal("lab_ppid");
        if (StringUtils.filled(lab_no)) {

            //lab annotation
            String other_id = StringUtils.noNull(labMea.getExtVal("other_id"));
            String annotation = getNonDumpNote(CaseManagementNoteLink.LABTEST, Long.valueOf(lab_no), other_id);
            if (StringUtils.filled(annotation))
                labResults.setPhysiciansNotes(annotation);

            HashMap<String, Object> labRoutingInfo = new HashMap<String, Object>();
            labRoutingInfo.putAll(ProviderLabRouting.getInfo(lab_no));

            String info = (String) labRoutingInfo.get("provider_no");
            if (info != null && !"0".equals(info)) {
                ProviderData pd = new ProviderData(info);
                if (StringUtils.noNull(pd.getOhip_no()).length() <= 6) {
                    LaboratoryResults.ResultReviewer reviewer = labResults.addNewResultReviewer();
                    reviewer.setOHIPPhysicianId(pd.getOhip_no());
                    Util.writeNameSimple(reviewer.addNewName(), pd.getFirst_name(), pd.getLast_name());
                }
            }
            String timestamp = (String) labRoutingInfo.get("timestamp");
            if (StringUtils.filled(timestamp)) {
                labResults.addNewDateTimeResultReviewed().setFullDate(Util.calDate(timestamp));
            }
        }
    }
}

From source file:com.k42b3.neodym.oauth.Oauth.java

public boolean accessToken() throws Exception {
    // add values
    HashMap<String, String> values = new HashMap<String, String>();

    String requestMethod = "GET";

    values.put("oauth_consumer_key", this.provider.getConsumerKey());
    values.put("oauth_token", this.token);
    values.put("oauth_signature_method", provider.getMethod());
    values.put("oauth_timestamp", this.getTimestamp());
    values.put("oauth_nonce", this.getNonce());
    values.put("oauth_verifier", this.verificationCode);

    // add get vars to values
    URL accessUrl = new URL(provider.getAccessUrl());
    values.putAll(parseQuery(accessUrl.getQuery()));

    // build base string
    String baseString = this.buildBaseString(requestMethod, provider.getAccessUrl(), values);

    // get signature
    SignatureInterface signature = this.getSignature();

    if (signature == null) {
        throw new Exception("Invalid signature method");
    }//  ww w. jav  a2s . co  m

    // build signature
    values.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), this.tokenSecret));

    // add header to request
    HashMap<String, String> header = new HashMap<String, String>();
    header.put("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(values));

    String responseContent = http.request(Http.GET, provider.getAccessUrl(), header);

    // parse response
    this.token = null;
    this.tokenSecret = null;

    HashMap<String, String> response = parseQuery(responseContent);
    Set<String> keys = response.keySet();

    for (String key : keys) {
        if (key.equals("oauth_token")) {
            this.token = response.get(key);

            logger.info("Received token: " + this.token);
        }

        if (key.equals("oauth_token_secret")) {
            this.tokenSecret = response.get(key);

            logger.info("Received token secret: " + this.tokenSecret);
        }
    }

    if (this.token == null) {
        throw new Exception("No oauth token received");
    }

    if (this.tokenSecret == null) {
        throw new Exception("No oauth token secret received");
    }

    return true;
}

From source file:de.fhg.fokus.famium.hbbtv.HbbTV.java

private HbbTvManager getHbbTvManager() {
    if (hbbTvManager == null) {
        hbbTvManager = new HbbTvManager(new HbbTvManager.DiscoverTerminalsCallback() {
            @Override//from  w ww.  j a  va 2  s .  co  m
            public void onDiscoverTerminals(Map<String, DialAppInfo> terminals) {
                synchronized (HbbTV.this) {
                    JSONArray arr = new JSONArray();
                    for (DialAppInfo terminal : terminals.values()) {
                        DialDevice device = terminal.getDialDevice();
                        HashMap<String, Object> copy = new HashMap<String, Object>();
                        copy.put("descriptionUrl", device.getDescriptionUrl());
                        copy.put("launchUrl", device.getApplicationUrl() + "/HbbTV");
                        copy.put("applicationUrl", device.getApplicationUrl());
                        copy.put("usn", device.getUSN());
                        copy.put("type", device.getType());
                        copy.put("friendlyName", device.getFriendlyName());
                        copy.put("manufacturer", device.getManufacturer());
                        copy.put("manufacturerUrl", device.getManufacturerUrl());
                        copy.put("modelDescription", device.getModelDescription());
                        copy.put("modelName", device.getModelName());
                        copy.put("udn", device.getUDN());
                        copy.put("state", terminal.getState());
                        copy.putAll(terminal.getAdditionalData());
                        arr.put(new JSONObject(copy));
                    }
                    for (CallbackContext callbackContext : getPendingDiscoveryRequests()) {
                        if (callbackContext != null) {
                            PluginResult result = new PluginResult(PluginResult.Status.OK, arr);
                            callbackContext.sendPluginResult(result);
                        }
                    }
                    getPendingDiscoveryRequests().clear();
                }
            }
        });
    }
    return hbbTvManager;
}

From source file:com.k42b3.neodym.oauth.Oauth.java

public boolean requestToken() throws Exception {
    // add values
    HashMap<String, String> values = new HashMap<String, String>();

    String requestMethod = "GET";

    values.put("oauth_consumer_key", this.provider.getConsumerKey());
    values.put("oauth_signature_method", provider.getMethod());
    values.put("oauth_timestamp", this.getTimestamp());
    values.put("oauth_nonce", this.getNonce());
    values.put("oauth_version", this.getVersion());
    values.put("oauth_callback", "oob");

    // add get vars to values
    URL requestUrl = new URL(provider.getRequestUrl());
    values.putAll(parseQuery(requestUrl.getQuery()));

    // build base string
    String baseString = this.buildBaseString(requestMethod, provider.getRequestUrl(), values);

    // get signature
    SignatureInterface signature = this.getSignature();

    if (signature == null) {
        throw new Exception("Invalid signature method");
    }/*from  ww w  .  j  a v  a 2s.  co m*/

    // build signature
    values.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), ""));

    // add header to request
    HashMap<String, String> header = new HashMap<String, String>();
    header.put("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(values));

    String responseContent = http.request(Http.GET, provider.getRequestUrl(), header);

    // parse response
    this.token = null;
    this.tokenSecret = null;
    this.callbackConfirmed = false;

    HashMap<String, String> response = parseQuery(responseContent);
    Set<String> keys = response.keySet();

    for (String key : keys) {
        if (key.equals("oauth_token")) {
            this.token = response.get(key);

            logger.info("Received token: " + this.token);
        }

        if (key.equals("oauth_token_secret")) {
            this.tokenSecret = response.get(key);

            logger.info("Received token secret: " + this.tokenSecret);
        }

        if (key.equals("oauth_callback_confirmed")) {
            this.tokenSecret = response.get(key);

            this.callbackConfirmed = response.get(key).equals("1");
        }
    }

    if (this.token == null) {
        throw new Exception("No oauth token received");
    }

    if (this.tokenSecret == null) {
        throw new Exception("No oauth token secret received");
    }

    if (this.callbackConfirmed != true) {
        throw new Exception("Callback was not confirmed");
    }

    return true;
}

From source file:org.telepatch.android.NotificationsController.java

public void showWearNotifications(boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 19) {
        return;//from   w  w w.j a  v  a2  s. c om
    }
    ArrayList<Long> sortedDialogs = new ArrayList<Long>();
    HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<Long, ArrayList<MessageObject>>();
    for (MessageObject messageObject : pushMessages) {
        long dialog_id = messageObject.getDialogId();
        if ((int) dialog_id == 0) {
            continue;
        }

        ArrayList<MessageObject> arrayList = messagesByDialogs.get(dialog_id);
        if (arrayList == null) {
            arrayList = new ArrayList<MessageObject>();
            messagesByDialogs.put(dialog_id, arrayList);
            sortedDialogs.add(0, dialog_id);
        }
        arrayList.add(messageObject);
    }

    HashMap<Long, Integer> oldIds = new HashMap<Long, Integer>();
    oldIds.putAll(wearNoticationsIds);
    wearNoticationsIds.clear();

    for (long dialog_id : sortedDialogs) {
        ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id);
        int max_id = messageObjects.get(0).messageOwner.id;
        TLRPC.Chat chat = null;
        TLRPC.User user = null;
        String name = null;
        if (dialog_id > 0) {
            user = MessagesController.getInstance().getUser((int) dialog_id);
            if (user == null) {
                continue;
            }
        } else {
            chat = MessagesController.getInstance().getChat(-(int) dialog_id);
            if (chat == null) {
                continue;
            }
        }
        if (chat != null) {
            name = chat.title;
        } else {
            name = ContactsController.formatName(user.first_name, user.last_name);
        }

        Integer notificationId = oldIds.get(dialog_id);
        if (notificationId == null) {
            notificationId = wearNotificationId++;
        } else {
            oldIds.remove(dialog_id);
        }

        Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class);
        replyIntent.putExtra("dialog_id", dialog_id);
        replyIntent.putExtra("max_id", max_id);
        PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
                .setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
        String replyToString;
        if (chat != null) {
            replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
        } else {
            replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
        }
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                replyToString, replyPendingIntent).addRemoteInput(remoteInput).build();

        String text = "";
        for (MessageObject messageObject : messageObjects) {
            String message = getStringForMessage(messageObject, false);
            if (message == null) {
                continue;
            }
            if (chat != null) {
                message = message.replace(" @ " + name, "");
            } else {
                message = message.replace(name + ": ", "").replace(name + " ", "");
            }
            if (text.length() > 0) {
                text += "\n\n";
            }
            text += message;
        }

        Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
        intent.setFlags(32768);
        if (chat != null) {
            intent.putExtra("chatId", chat.id);
        } else if (user != null) {
            intent.putExtra("userId", user.id);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                ApplicationLoader.applicationContext).setContentTitle(name)
                        .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text)
                        .setGroupSummary(false).setContentIntent(contentIntent)
                        .extend(new NotificationCompat.WearableExtender().addAction(action));

        notificationManager.notify(notificationId, builder.build());
        wearNoticationsIds.put(dialog_id, notificationId);
    }

    for (HashMap.Entry<Long, Integer> entry : oldIds.entrySet()) {
        notificationManager.cancel(entry.getValue());
    }
}

From source file:de.ingrid.ibus.comm.Bus.java

private IngridHits normalizeScores(List<IngridHits> resultSet, boolean skipNormalization) {
    if (fLogger.isDebugEnabled()) {
        fLogger.debug("normalize the results");
    }//from   ww  w.j  a  v a2 s.c o  m

    int totalHits = 0;
    int count = resultSet.size();
    List<IngridHit> documents = new LinkedList<IngridHit>();
    for (int i = 0; i < count; i++) {
        float maxScore = 1.0f;
        IngridHits hitContainer = resultSet.get(i);
        totalHits += hitContainer.length();
        if (hitContainer.getHits().length > 0) {
            Float boost = this.fRegistry.getGlobalRankingBoost(hitContainer.getPlugId());
            IngridHit[] resultHits = hitContainer.getHits();
            if (null != boost) {
                for (int j = 0; j < resultHits.length; j++) {
                    float score = 1.0f;
                    if (hitContainer.isRanked()) {
                        score = resultHits[j].getScore();
                        score = score * boost.floatValue();
                    }
                    resultHits[j].setScore(score);
                }
            }

            // normalize scores of the results of this iPlug
            // so maxScore will never get bigger than 1 now!
            if (!skipNormalization && maxScore < resultHits[0].getScore()) {
                normalizeHits(hitContainer, resultHits[0].getScore());
            }
        }

        IngridHit[] toAddHits = hitContainer.getHits();
        if (toAddHits != null) {
            documents.addAll(Arrays.asList(toAddHits));
        }
    }

    IngridHits result = new IngridHits(totalHits,
            sortHits((IngridHit[]) documents.toArray(new IngridHit[documents.size()])));

    // add timings for the corresponding iplugs
    HashMap<String, Long> timings = new HashMap<String, Long>();
    for (IngridHits hits : resultSet) {
        timings.putAll(hits.getSearchTimings());
    }
    result.setSearchTimings(timings);

    documents.clear();
    documents = null;

    return result;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private List<String> getNestedRoles(DirContext dirContext, List<String> roleList) {

    HashMap<String, List<String>> roleMemberOfMap = new HashMap<String, List<String>>();
    roleMemberOfMap.putAll(getRoleMemberOfMap(dirContext));

    List<String> mergedList = mergeRoles(roleList, roleMemberOfMap);

    return mergedList;
}