Example usage for java.util HashMap remove

List of usage examples for java.util HashMap remove

Introduction

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

Prototype

public V remove(Object key) 

Source Link

Document

Removes the mapping for the specified key from this map if present.

Usage

From source file:edu.duke.cabig.c3pr.web.ajax.StudyAjaxFacade.java

/**
 * Removes the pre assigned staff. /*  w  w w.  j av  a  2s .c om*/
 * Looks at the csm_group_role_pg and removes them from the list to be returned.
 *
 * @param studyScopedRSList the study scoped rs list
 * @param studyId the study id
 * @param hcs the selected site 
 */
private void removePreAssignedStaff(HashMap<PersonUser, List<String>> studyScopedRSMap, String studyId) {
    Study study = studyDao.getById(Integer.valueOf(studyId));

    //this is a map of all staff and roles that have access to the selected organization and study
    HashMap<PersonUser, List<String>> preAssignedStaffMap = new HashMap<PersonUser, List<String>>();
    boolean hasAccess = false;
    for (PersonUser rs : studyScopedRSMap.keySet()) {
        for (String roleName : studyScopedRSMap.get(rs)) {
            hasAccess = studyPersonnelDao.isStaffAssignedToStudy(rs, study, roleName);
            if (hasAccess) {
                if (preAssignedStaffMap.containsKey(rs)) {
                    ((ArrayList<String>) preAssignedStaffMap.get(rs)).add(roleName);
                } else {
                    ArrayList<String> roleList = new ArrayList<String>();
                    roleList.add(roleName);
                    preAssignedStaffMap.put(rs, roleList);
                }
            }
        }
    }

    //remove pre-assigned staff or role from the map to be returned
    for (PersonUser rs : preAssignedStaffMap.keySet()) {
        for (String roleName : preAssignedStaffMap.get(rs)) {
            //remove the role
            ((ArrayList<String>) studyScopedRSMap.get(rs)).remove(roleName);
        }
        //remove the staff itself if it has no roles against it
        if (((ArrayList<String>) studyScopedRSMap.get(rs)) == null
                || ((ArrayList<String>) studyScopedRSMap.get(rs)).size() == 0) {
            studyScopedRSMap.remove(rs);
        }
    }
}

From source file:io.bifroest.commons.boot.BootLoaderNG.java

/**
 * Calculates the systems boot order. This is an iterative process: At
 * first, from a list with all available systems, all systems with no
 * dependencies are removed. This is repeated until the list is empty. If
 * there are systems still remaining, there is a dependency misconfiguration
 * and a CircularDependencyException is raised.
 *
 * @return A list with systems ordered by boot priority. The first element
 * needs to start first, the second after and so on.
 * @throws CircularDependencyException If two or more systems are
 * misconfigured, a circular dependency can occur. This happens e.g. if
 * system A depends on system B and system B also requires system A. This
 * cannot be resolved and an exception is thrown.
 *///  w  ww. jav  a2 s  .co m
private List<Subsystem<E>> getBootOrder() throws CircularDependencyException {
    HashMap<String, Subsystem<E>> bootSystems = new HashMap<>();
    HashMap<String, List<String>> systemDependencies = new HashMap<>();
    List<Subsystem<E>> result = new ArrayList<>();

    // shuffle systems to boot, so no one can forget system dependencies
    Collections.shuffle(this.systemsToBoot);

    this.systemsToBoot.stream().forEach((system) -> {
        bootSystems.put(system.getSystemIdentifier(), system);
        systemDependencies.put(system.getSystemIdentifier(), system.getRequiredSystems().stream()
                .filter(dep -> !dep.equals(system.getSystemIdentifier())).collect(Collectors.toList()));
    });
    // while there are dependencies to solve
    while (!systemDependencies.isEmpty()) {
        // Get all nodes without any dependency            
        Set<String> keys = systemDependencies.keySet();
        List<String> resolved = new ArrayList<>();
        keys.stream().forEach((key) -> {
            log.trace("Trying to resolve {}", key);
            Collection<String> dependencies = systemDependencies.get(key);
            log.trace("Found dependencies: {}", dependencies);
            if (dependencies == null || dependencies.isEmpty()) {
                log.trace("Marking {} as resolved", key);
                resolved.add(key);
            }
        });
        // if resolved is empty, we have a loop in the graph            
        if (resolved.isEmpty()) {
            String msg = "Loop in graph! This should not happen. Check your dependencies! Remaining systems: "
                    + keys.toString();
            throw new CircularDependencyException(msg, systemDependencies);
        }

        // remove systemsToBoot found from dependency graph
        resolved.stream().forEach((systemIdentifier) -> {
            systemDependencies.remove(systemIdentifier);
            result.add(bootSystems.get(systemIdentifier));
        });

        // remove dependencies
        Set<String> systemDependenciesKeys = systemDependencies.keySet();
        systemDependenciesKeys.stream().map((key) -> systemDependencies.get(key)).forEach((values) -> {
            resolved.stream().forEach((resolvedValue) -> {
                values.removeIf(v -> v.equals(resolvedValue));
            });
        });
    }
    return result;
}

From source file:org.apache.sysml.hops.ipa.InterProceduralAnalysis.java

private void removeCheckpointBeforeUpdate(DMLProgram dmlp) throws HopsException {
    //approach: scan over top-level program (guaranteed to be unconditional),
    //collect checkpoints; determine if used before update; remove first checkpoint
    //on second checkpoint if update in between and not used before update

    HashMap<String, Hop> chkpointCand = new HashMap<String, Hop>();

    for (StatementBlock sb : dmlp.getStatementBlocks()) {
        //prune candidates (used before updated)
        Set<String> cands = new HashSet<String>(chkpointCand.keySet());
        for (String cand : cands)
            if (sb.variablesRead().containsVariable(cand) && !sb.variablesUpdated().containsVariable(cand)) {
                //note: variableRead might include false positives due to meta 
                //data operations like nrow(X) or operations removed by rewrites 
                //double check hops on basic blocks; otherwise worst-case
                boolean skipRemove = false;
                if (sb.get_hops() != null) {
                    Hop.resetVisitStatus(sb.get_hops());
                    skipRemove = true;//from w  w w  .j  a  v  a2 s  . c  o m
                    for (Hop root : sb.get_hops())
                        skipRemove &= !HopRewriteUtils.rContainsRead(root, cand, false);
                }
                if (!skipRemove)
                    chkpointCand.remove(cand);
            }

        //prune candidates (updated in conditional control flow)
        Set<String> cands2 = new HashSet<String>(chkpointCand.keySet());
        if (sb instanceof IfStatementBlock || sb instanceof WhileStatementBlock
                || sb instanceof ForStatementBlock) {
            for (String cand : cands2)
                if (sb.variablesUpdated().containsVariable(cand)) {
                    chkpointCand.remove(cand);
                }
        }
        //prune candidates (updated w/ multiple reads) 
        else {
            for (String cand : cands2)
                if (sb.variablesUpdated().containsVariable(cand) && sb.get_hops() != null) {
                    Hop.resetVisitStatus(sb.get_hops());
                    for (Hop root : sb.get_hops())
                        if (root.getName().equals(cand) && !HopRewriteUtils.rHasSimpleReadChain(root, cand)) {
                            chkpointCand.remove(cand);
                        }
                }
        }

        //collect checkpoints and remove unnecessary checkpoints
        ArrayList<Hop> tmp = collectCheckpoints(sb.get_hops());
        for (Hop chkpoint : tmp) {
            if (chkpointCand.containsKey(chkpoint.getName())) {
                chkpointCand.get(chkpoint.getName()).setRequiresCheckpoint(false);
            }
            chkpointCand.put(chkpoint.getName(), chkpoint);
        }

    }
}

From source file:org.apache.sysml.hops.ipa.InterProceduralAnalysis.java

private void moveCheckpointAfterUpdate(DMLProgram dmlp) throws HopsException {
    //approach: scan over top-level program (guaranteed to be unconditional),
    //collect checkpoints; determine if used before update; move first checkpoint
    //after update if not used before update (best effort move which often avoids
    //the second checkpoint on loops even though used in between)

    HashMap<String, Hop> chkpointCand = new HashMap<String, Hop>();

    for (StatementBlock sb : dmlp.getStatementBlocks()) {
        //prune candidates (used before updated)
        Set<String> cands = new HashSet<String>(chkpointCand.keySet());
        for (String cand : cands)
            if (sb.variablesRead().containsVariable(cand) && !sb.variablesUpdated().containsVariable(cand)) {
                //note: variableRead might include false positives due to meta 
                //data operations like nrow(X) or operations removed by rewrites 
                //double check hops on basic blocks; otherwise worst-case
                boolean skipRemove = false;
                if (sb.get_hops() != null) {
                    Hop.resetVisitStatus(sb.get_hops());
                    skipRemove = true;// ww w.j  ava2s .  c  o  m
                    for (Hop root : sb.get_hops())
                        skipRemove &= !HopRewriteUtils.rContainsRead(root, cand, false);
                }
                if (!skipRemove)
                    chkpointCand.remove(cand);
            }

        //prune candidates (updated in conditional control flow)
        Set<String> cands2 = new HashSet<String>(chkpointCand.keySet());
        if (sb instanceof IfStatementBlock || sb instanceof WhileStatementBlock
                || sb instanceof ForStatementBlock) {
            for (String cand : cands2)
                if (sb.variablesUpdated().containsVariable(cand)) {
                    chkpointCand.remove(cand);
                }
        }
        //move checkpoint after update with simple read chain 
        //(note: right now this only applies if the checkpoints comes from a previous
        //statement block, within-dag checkpoints should be handled during injection)
        else {
            for (String cand : cands2)
                if (sb.variablesUpdated().containsVariable(cand) && sb.get_hops() != null) {
                    Hop.resetVisitStatus(sb.get_hops());
                    for (Hop root : sb.get_hops())
                        if (root.getName().equals(cand)) {
                            if (HopRewriteUtils.rHasSimpleReadChain(root, cand)) {
                                chkpointCand.get(cand).setRequiresCheckpoint(false);
                                root.getInput().get(0).setRequiresCheckpoint(true);
                                chkpointCand.put(cand, root.getInput().get(0));
                            } else
                                chkpointCand.remove(cand);
                        }
                }
        }

        //collect checkpoints
        ArrayList<Hop> tmp = collectCheckpoints(sb.get_hops());
        for (Hop chkpoint : tmp) {
            chkpointCand.put(chkpoint.getName(), chkpoint);
        }
    }
}

From source file:configuration.Util.java

/**
 * IN TEST for Docker/*from  ww  w  . jav  a2s .co m*/
 * Compare a table of path from inputs files and return an hashmap of string local<>string in docker
 * Problem1 to compare canonical path the minimum path is the root and it's useless
 * Problem2 it probably not the best way to share
 * => we have choosed to share a folder per inputs connected to a folder in Docker
 * Added by JG 2017
 * @param tab a table of string for files
 * @param doinputs the inputs path in docker container
 * @return string of inputs files and the string in docker
 * 
 */
public static HashMap<String, String> compareTabFilePath(String[] tab, String doInputs) {
    HashMap<String, Integer> finalFilesPath = new HashMap<String, Integer>();
    HashMap<String, String> filesPathName = new HashMap<String, String>();
    String[] tabTmp = tab;
    for (String p : tabTmp) {
        if (p != "") {
            String path = getParentOfFile(p);
            String name = getFileName(p);
            filesPathName.put(path, name);
            p = path;
        }
    }
    for (int i = 0; i < tabTmp.length - 1; i++) {
        for (String path : filesPathName.keySet()) {
            if (tab[i] != "" && path != "") {
                String[] r = compareTwoFilePath(tabTmp[i], path);
                if (r[0] != "") {
                    if (finalFilesPath.isEmpty()) {
                        finalFilesPath.put(r[0], 0);
                    }
                    for (String p : finalFilesPath.keySet()) {
                        String[] r2 = compareTwoFilePath(r[0], p);
                        if (r2[0] != r[0]) {
                            finalFilesPath.remove(r[0]);
                            finalFilesPath.put(r2[0], 0);
                        }
                    }

                }
            }
        }
    }
    HashMap<String, String> inputsFilesPath = new HashMap<String, String>();
    for (String k : finalFilesPath.keySet()) {
        inputsFilesPath.put(k, doInputs + Integer.toString(finalFilesPath.get(k)) + "/");
    }
    return inputsFilesPath;
}

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

public void showWearNotifications(boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 19) {
        return;/*from   w  w w  . ja v a2 s  .  com*/
    }
    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:com.clevertap.cordova.CleverTapPlugin.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    Log.d(LOG_TAG, "handling action " + action);

    boolean haveError = false;
    String errorMsg = "unhandled CleverTapPlugin action";

    PluginResult result = null;/*from www  .  j  a  v a  2 s  . com*/

    if (!checkCleverTapInitialized()) {
        result = new PluginResult(PluginResult.Status.ERROR, "CleverTap API not initialized");
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("registerPush")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("setPushTokenAsString")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    else if (action.equals("setDebugLevel")) {
        int level = (args.length() == 1 ? args.getInt(0) : -1);
        if (level >= 0) {
            CleverTapAPI.setDebugLevel(level);
            result = new PluginResult(PluginResult.Status.NO_RESULT);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
            return true;
        }

    }

    else if (action.equals("enablePersonalization")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                cleverTap.enablePersonalization();
                PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;

    }

    else if (action.equals("recordEventWithName")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("recordEventWithNameAndProps")) {
        String eventName = null;
        JSONObject jsonProps;
        HashMap<String, Object> _props = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                eventName = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "eventName cannot be null";
            }
            if (!args.isNull(1)) {
                jsonProps = args.getJSONObject(1);
                try {
                    _props = toMap(jsonProps);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing event properties";
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _eventName = eventName;
            final HashMap<String, Object> props = _props;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(_eventName, props);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("recordChargedEventWithDetailsAndItems")) {
        JSONObject jsonDetails;
        JSONArray jsonItems;
        HashMap<String, Object> _details = null;
        ArrayList<HashMap<String, Object>> _items = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                jsonDetails = args.getJSONObject(0);
                try {
                    _details = toMap(jsonDetails);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
            if (!args.isNull(1)) {
                jsonItems = args.getJSONArray(1);
                try {
                    _items = toArrayListOfStringObjectMaps(jsonItems);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final HashMap<String, Object> details = _details;
            final ArrayList<HashMap<String, Object>> items = _items;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        cleverTap.event.push(CleverTapAPI.CHARGED_EVENT, details, items);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (InvalidEventNameException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;
        }
    }

    else if (action.equals("eventGetFirstTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double first = cleverTap.event.getFirstTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) first);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetLastTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double lastTime = cleverTap.event.getLastTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) lastTime);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetOccurrences")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    int num = cleverTap.event.getCount(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, num);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetDetails")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    EventDetail details = cleverTap.event.getDetails(eventName);
                    try {
                        JSONObject jsonDetails = CleverTapPlugin.eventDetailsToJSON(details);
                        PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (JSONException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("getEventHistory")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                Map<String, EventDetail> history = cleverTap.event.getHistory();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.eventHistoryToJSON(history);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

    else if (action.equals("setLocation")) {
        Double lat = null;
        Double lon = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                lat = args.getDouble(0);
            } else {
                haveError = true;
                errorMsg = "lat cannot be null";
            }
            if (!args.isNull(1)) {
                lon = args.getDouble(1);
            } else {
                haveError = true;
                errorMsg = "lon cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final Location location = new Location("CleverTapPlugin");
            location.setLatitude(lat);
            location.setLongitude(lon);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.updateLocation(location);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSet")) {
        JSONObject jsonProfile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonProfile = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonProfile = jsonProfile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        HashMap<String, Object> profile = toMap(_jsonProfile);
                        String dob = (String) profile.get("DOB");
                        if (dob != null) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
                            try {
                                Date date = format.parse(dob);
                                profile.put("DOB", date);
                            } catch (ParseException e) {
                                profile.remove("DOB");
                                Log.d(LOG_TAG, "invalid DOB format in profileSet");
                            }
                        }

                        cleverTap.profile.push(profile);

                    } catch (Exception e) {
                        Log.d(LOG_TAG, "Error setting profile " + e.getLocalizedMessage());
                    }

                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });

            return true;
        }
    }

    else if (action.equals("profileSetGraphUser")) {
        JSONObject jsonGraphUser = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGraphUser = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonGraphUser = jsonGraphUser;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.pushFacebookUser(_jsonGraphUser);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSetGooglePlusUser")) {
        JSONObject jsonGooglePlusUser;
        HashMap<String, Object> _profile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGooglePlusUser = args.getJSONObject(0);
                try {
                    _profile = toMapFromGooglePlusUser(jsonGooglePlusUser);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final HashMap<String, Object> profile = _profile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.push(profile);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileGetProperty")) {
        final String propertyName = (args.length() == 1 ? args.getString(0) : null);
        if (propertyName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult _result;
                    Object prop = cleverTap.profile.getProperty(propertyName);

                    if (prop instanceof JSONArray) {
                        JSONArray _prop = (JSONArray) prop;
                        _result = new PluginResult(PluginResult.Status.OK, _prop);

                    } else {
                        String _prop;
                        if (prop != null) {
                            _prop = prop.toString();
                        } else {
                            _prop = null;
                        }
                        _result = new PluginResult(PluginResult.Status.OK, _prop);
                    }

                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "propertyName cannot be null";
        }
    }

    else if (action.equals("profileGetCleverTapID")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String CleverTapID = cleverTap.getCleverTapID();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, CleverTapID);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("profileRemoveValueForKey")) {
        final String key = (args.length() == 1 ? args.getString(0) : null);
        if (key != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeValueForKey(key);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "property key cannot be null";
        }
    }

    else if (action.equals("profileSetMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.setMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.addMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    } else if (action.equals("profileRemoveMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.removeMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.addMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileRemoveMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("sessionGetTimeElapsed")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getTimeElapsed();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetTotalVisits")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getTotalVisits();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetScreenCount")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getScreenCount();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetPreviousVisitTime")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getPreviousVisitTime();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetUTMDetails")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                UTMDetail details = cleverTap.session.getUTMDetails();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.utmDetailsToJSON(details);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

    result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
    result.setKeepCallback(true);
    callbackContext.sendPluginResult(result);
    return true;
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

public void init(String idpName, ServletContext ctx, HashMap<String, Attribute> init,
        HashMap<String, HashMap<String, Attribute>> trustCfg, MapIdentity mapper) {
    final String localIdPName = idpName;
    this.idpName = idpName;
    this.trusts = new HashMap<String, OpenIDConnectTrust>();
    for (String trustName : trustCfg.keySet()) {
        HashMap<String, Attribute> attrs = trustCfg.get(trustName);
        OpenIDConnectTrust trust = new OpenIDConnectTrust();
        trust.setClientID(attrs.get("clientID").getValues().get(0));
        trust.setClientSecret(attrs.get("clientSecret").getValues().get(0));
        trust.setRedirectURI(attrs.get("redirectURI").getValues().get(0));
        trust.setCodeLastmileKeyName(attrs.get("codeLastMileKeyName").getValues().get(0));
        trust.setAuthChain(attrs.get("authChainName").getValues().get(0));
        trust.setCodeTokenTimeToLive(Long.parseLong(attrs.get("codeTokenSkewMilis").getValues().get(0)));
        trust.setAccessTokenTimeToLive(Long.parseLong(attrs.get("accessTokenTimeToLive").getValues().get(0)));
        trust.setAccessTokenSkewMillis(Long.parseLong(attrs.get("accessTokenSkewMillis").getValues().get(0)));

        if (attrs.get("verifyRedirect") == null) {
            trust.setVerifyRedirect(true);
        } else {/*  ww w  .  j a  va  2  s.  c  o  m*/
            trust.setVerifyRedirect(attrs.get("verifyRedirect").getValues().get(0).equalsIgnoreCase("true"));
        }

        trust.setTrustName(trustName);

        if (attrs.get("publicEndpoint") != null
                && attrs.get("publicEndpoint").getValues().get(0).equalsIgnoreCase("true")) {
            trust.setPublicEndpoint(true);
        }

        trusts.put(trust.getClientID(), trust);

    }

    this.mapper = mapper;
    this.jwtSigningKeyName = init.get("jwtSigningKey").getValues().get(0);

    HashMap<String, OpenIDConnectIdP> oidcIdPs = (HashMap<String, OpenIDConnectIdP>) GlobalEntries
            .getGlobalEntries().get(UNISON_OPENIDCONNECT_IDPS);
    if (oidcIdPs == null) {
        oidcIdPs = new HashMap<String, OpenIDConnectIdP>();
        GlobalEntries.getGlobalEntries().set(UNISON_OPENIDCONNECT_IDPS, oidcIdPs);
    }

    oidcIdPs.put(this.idpName, this);

    GlobalEntries.getGlobalEntries().getConfigManager().addThread(new StopableThread() {

        @Override
        public void run() {
            //do nothing

        }

        @Override
        public void stop() {
            HashMap<String, OpenIDConnectIdP> oidcIdPs = (HashMap<String, OpenIDConnectIdP>) GlobalEntries
                    .getGlobalEntries().get(UNISON_OPENIDCONNECT_IDPS);
            if (oidcIdPs != null) {
                oidcIdPs.remove(localIdPName);
            }

        }
    });

    String driver = init.get("driver").getValues().get(0);
    logger.info("Driver : '" + driver + "'");

    String url = init.get("url").getValues().get(0);
    ;
    logger.info("URL : " + url);
    String user = init.get("user").getValues().get(0);
    ;
    logger.info("User : " + user);
    String pwd = init.get("password").getValues().get(0);
    ;
    logger.info("Password : **********");

    int maxCons = Integer.parseInt(init.get("maxCons").getValues().get(0));
    logger.info("Max Cons : " + maxCons);
    int maxIdleCons = Integer.parseInt(init.get("maxIdleCons").getValues().get(0));
    logger.info("maxIdleCons : " + maxIdleCons);

    String dialect = init.get("dialect").getValues().get(0);
    logger.info("Hibernate Dialect : '" + dialect + "'");

    String validationQuery = init.get("validationQuery").getValues().get(0);
    logger.info("Validation Query : '" + validationQuery + "'");

    String hibernateConfig = init.get("hibernateConfig") != null
            ? init.get("hibernateConfig").getValues().get(0)
            : null;
    logger.info("HIbernate mapping file : '" + hibernateConfig + "'");

    String hibernateCreateSchema = init.get("hibernateCreateSchema") != null
            ? init.get("hibernateCreateSchema").getValues().get(0)
            : null;
    logger.info("Can create schema : '" + hibernateCreateSchema + "'");

    this.initializeHibernate(driver, user, pwd, url, dialect, maxCons, maxIdleCons, validationQuery,
            hibernateConfig, hibernateCreateSchema);

}

From source file:org.openbravo.advpaymentmngt.actionHandler.ModifyPaymentPlanActionHandler.java

/**
 * Given a list of payment schedule element and a list of amounts associated to orders, creates
 * the payment schedule details for the given payment schedule element
 * //from w w w.  ja  v a  2s  .  com
 */
private HashMap<FIN_PaymentSchedule, BigDecimal> createPaymentScheduleDetail(FIN_PaymentSchedule invoicePS,
        HashMap<FIN_PaymentSchedule, BigDecimal> ordersProvided) {
    HashMap<FIN_PaymentSchedule, BigDecimal> orders = ordersProvided;
    Iterator<FIN_PaymentSchedule> ite = orders.keySet().iterator();
    BigDecimal amount = getPendingPSAmounts(invoicePS);
    List<FIN_PaymentSchedule> lOrdersToRemove = new ArrayList<FIN_PaymentSchedule>();
    FIN_PaymentSchedule orderPS = null;
    BigDecimal orderAmount = BigDecimal.ZERO;
    if (orders.containsKey(null)) {
        orderAmount = orders.get(null);
    } else {
        lOrdersToRemove.add(null);
    }
    while (amount.compareTo(BigDecimal.ZERO) != 0 && ite.hasNext()) {
        if (lOrdersToRemove.contains(orderPS) || orderAmount.compareTo(BigDecimal.ZERO) == 0) {
            orderPS = ite.next();
            orderAmount = orders.get(orderPS);
        }
        if (amount.abs().compareTo(orderAmount.abs()) >= 0) {
            if (orderAmount.compareTo(BigDecimal.ZERO) != 0) {
                dao.getNewPaymentScheduleDetail(invoicePS, orderPS, orderAmount, BigDecimal.ZERO, null);
            }
            amount = amount.subtract(orderAmount);
            orderAmount = BigDecimal.ZERO;
            lOrdersToRemove.add(orderPS);
        } else {
            if (amount.compareTo(BigDecimal.ZERO) != 0) {
                dao.getNewPaymentScheduleDetail(invoicePS, orderPS, amount, BigDecimal.ZERO, null);
            }
            orderAmount = orderAmount.subtract(amount);
            amount = BigDecimal.ZERO;
        }
        orders.put(orderPS, orderAmount);
    }
    OBDal.getInstance().flush();

    for (FIN_PaymentSchedule ps : lOrdersToRemove) {
        orders.remove(ps);
    }
    return orders;
}

From source file:me.cpwc.nibblegram.android.NotificationsController.java

public void showWearNotifications(boolean notifyAboutLast) {
    if (Build.VERSION.SDK_INT < 19) {
        return;//from w  ww.j  a v a2 s  .c  o m
    }
    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))
                        .setCategory(NotificationCompat.CATEGORY_MESSAGE);

        if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
            builder.addPerson("tel:+" + user.phone);
        }

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

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