Example usage for java.util.concurrent ConcurrentHashMap containsKey

List of usage examples for java.util.concurrent ConcurrentHashMap containsKey

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentHashMap containsKey.

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Tests if the specified object is a key in this table.

Usage

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ObjectNode buildLinksNode(final ObjectMapper objectMapper, final Map<URI, ObjectNode> schemaNodes,
        final Map<URI, LinkRelation> linkRelationCache, final ApiNavigator apiNavigator,
        final Resource resource, final Prototype defaultPrototype) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null;

    final ObjectNode linksNode = objectMapper.createObjectNode();

    final Set<URI> responseSchemaUris = new HashSet<>();
    if (defaultSchemaUri != null) {
        responseSchemaUris.add(defaultSchemaUri);
    }//w  ww  . ja v a2  s  .co  m

    for (final Method method : Method.values()) {
        final Set<URI> methodResponseSchemaUris = resource.getResponseSchemaUris(method);
        if (methodResponseSchemaUris != null && !methodResponseSchemaUris.isEmpty()) {
            responseSchemaUris.addAll(methodResponseSchemaUris);
        }
    }

    final ConcurrentHashMap<URI, LinkTemplate> linkTemplates = resource.getLinkTemplates();

    for (final URI schemaUri : responseSchemaUris) {
        final Prototype prototype = schemaLoader.getPrototype(schemaUri);
        final SortedMap<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots();
        if (linkProtoSlots == null || linkProtoSlots.isEmpty()) {
            continue;
        }

        final ObjectNode linkTemplatesNode = objectMapper.createObjectNode();

        final Set<URI> linkRelationUris = linkProtoSlots.keySet();
        for (final URI linkRelationUri : linkRelationUris) {
            final LinkProtoSlot linkProtoSlot = linkProtoSlots.get(linkRelationUri);

            if (schemaLoader.getDocumentSchemaUri().equals(linkProtoSlot.getDeclaringSchemaUri())) {
                // Skip over the built-in system-level link relations (which are all self-referential).
                continue;
            }

            final ObjectNode linkTemplateNode = objectMapper.createObjectNode();
            final String linkSlotName = linkProtoSlot.getName();
            linkTemplatesNode.put(linkSlotName, linkTemplateNode);

            final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);
            final Method method = linkRelation.getMethod();

            linkTemplateNode.put(PropertyName.method.name(), method.getProtocolGivenName());
            linkTemplateNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));
            linkTemplateNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle());

            final URI responseSchemaUri;
            final URI requestSchemaUri;

            if (linkTemplates.containsKey(linkRelationUri)) {
                final LinkTemplate linkTemplate = linkTemplates.get(linkRelationUri);
                responseSchemaUri = linkTemplate.getResponseSchemaUri();
                requestSchemaUri = linkTemplate.getRequestSchemaUri();

                final UUID endPointId = linkTemplate.getEndPointId();
                if (endPointId != null) {
                    final Resource endPointResource = apiNavigator.getResource(endPointId);

                    final ObjectNode endPointNode = objectMapper.createObjectNode();

                    endPointNode.put(PropertyName.id.name(), syntaxLoader.formatSyntaxValue(endPointId));
                    endPointNode.put(PropertyName.pathSegment.name(), endPointResource.getPathSegment());
                    endPointNode.put(PropertyName.fullPath.name(), endPointResource.getPathText());
                    endPointNode.put(PropertyName.uriTemplate.name(),
                            endPointResource.getUriTemplate().getUriTemplateString());

                    linkTemplateNode.put(PropertyName.endpoint.name(), endPointNode);
                }

            } else {
                responseSchemaUri = linkProtoSlot.getResponseSchemaUri();
                requestSchemaUri = linkProtoSlot.getRequestSchemaUri();
            }

            if (responseSchemaUri != null) {
                final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                        responseSchemaUri, schemaLoader);
                linkTemplateNode.put(PropertyName.responseSchema.name(), responseSchemaNode);
            }

            if (requestSchemaUri != null) {
                final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes, requestSchemaUri,
                        schemaLoader);
                linkTemplateNode.put(PropertyName.requestSchema.name(), requestSchemaNode);
            }

            final String signature = buildLinkSignature(linkSlotName, responseSchemaUri, requestSchemaUri,
                    schemaUri);
            linkTemplateNode.put(PropertyName.signature.name(), signature);
        }

        if (linkTemplatesNode.size() > 0) {
            final ObjectNode schemaNode = objectMapper.createObjectNode();
            final ObjectNode schemaDetailsNode = getSchemaNode(objectMapper, schemaNodes, schemaUri,
                    schemaLoader);
            schemaNode.put(PropertyName.schema.name(), schemaDetailsNode);
            schemaNode.put(PropertyName.linkTemplates.name(), linkTemplatesNode);
            linksNode.put(prototype.getUniqueName().getLocalName(), schemaNode);
        }
    }

    return linksNode;
}

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

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);//  www . ja v a2 s .  co m
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;//from   w  ww .j a v a  2  s .  co m

    try {
        String configFilePath = null;
        String json = null;
        JSONObject jObj = null;

        parseJson: {
            //If a command line argument is passed then assume it is the config file.
            //Otherwise use the default location
            if (args.length > 0) {
                configFilePath = args[0];
            } else {
                configFilePath = DBMojoServer.defaultConfigPath;
            }

            try {
                json = Util.fileToString(configFilePath);
            } catch (Exception fileEx) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', could not be found and/or read");
            }

            if (json == null || json.equals("")) {
                throw new Exception("the specified config file, '" + configFilePath + "', is empty");
            }

            try {
                jObj = new JSONObject(json);
            } catch (Exception je) {
                throw new Exception(
                        "the specified config file, '" + configFilePath + "', does not contain valid JSON");
            }
        }

        //Load basic config data
        short serverPort = (short) jObj.optInt("serverPort");
        boolean useGzip = jObj.optBoolean("useGzip");
        short maxConcReq = (short) jObj.optInt("maxConcurrentRequests");
        String accessLogPath = jObj.optString("accessLogPath");
        String errorLogPath = jObj.optString("errorLogPath");
        String debugLogPath = jObj.optString("debugLogPath");

        checkMaxConcurrentReqeusts: {
            if (maxConcReq <= 0) {
                throw new Exception("please set the max concurrent requests to " + "a resonable number");
            }
        }

        checkServerPort: {
            //Make sure serverPort was specified
            if (serverPort <= 0) {
                throw new Exception("the server port was not specified");
            }

            //Make sure serverPort is not in use
            ServerSocket tSocket = null;
            try {
                tSocket = new ServerSocket(serverPort);
            } catch (Exception se) {
                tSocket = null;
                throw new Exception("the server port specified is already in use");
            } finally {
                if (tSocket != null) {
                    tSocket.close();
                }
                tSocket = null;
            }
        }

        startLogs: {
            if (!accessLogPath.equals("")) {
                //Make sure accessLogPath exists
                Util.pathExists(accessLogPath, true);
                //Start logging
                AccessLog.start(accessLogPath);
            }

            if (!errorLogPath.equals("")) {
                //Make sure errorLogPath exists
                Util.pathExists(errorLogPath, true);
                //Start logging
                ErrorLog.start(errorLogPath);
            }

            if (!debugLogPath.equals("")) {
                //Make sure debugLogPath exists
                Util.pathExists(debugLogPath, true);
                //Start logging
                DebugLog.start(debugLogPath);
            }
        }

        ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>();
        loadDbAlaises: {
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            final JSONArray dbAliases = jObj.getJSONArray("dbAliases");

            for (int i = 0; i < dbAliases.length(); i++) {
                final JSONObject tObj = dbAliases.getJSONObject(i);
                final String tAlias = tObj.getString("alias");
                final String tDriver = tObj.getString("driver");
                final String tDsn = tObj.getString("dsn");
                final String tUsername = tObj.getString("username");
                final String tPassword = tObj.getString("password");
                int tMaxConnections = tObj.getInt("maxConnections");
                //Seconds
                int tExpirationTime = tObj.getInt("expirationTime") * 1000;
                //Seconds
                int tConnectTimeout = tObj.getInt("connectTimeout");

                //Make sure each alias is named
                if (tAlias.equals("")) {
                    throw new Exception("alias #" + i + " is missing a name");
                }

                //Attempt to load each JDBC driver to ensure they are on the class path
                try {
                    Class aClass = classLoader.loadClass(tDriver);
                } catch (ClassNotFoundException cnf) {
                    throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path");
                }

                //Make sure each alias has a JDBC connection string
                if (tDsn.equals("")) {
                    throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'");
                }

                //Attempt to create a JDBC Connection
                ConnectionPool tPool;
                try {
                    tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias);
                    tPool.checkOut(false);
                } catch (Exception e) {
                    throw new Exception(
                            "JDBC Connection cannot be established " + "for database '" + tAlias + "'");
                } finally {
                    tPool = null;
                }

                //If the max connections option is not set for this alias 
                //then set it to 25
                if (tMaxConnections <= 0) {
                    tMaxConnections = 25;
                    System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '"
                            + tAlias + "' using 25");
                }

                //If the connection expiration time is not set for this alias then 
                //set it to 30 seconds
                if (tExpirationTime <= 0) {
                    tExpirationTime = 30;
                    System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '"
                            + tAlias + "' using 30 seconds");
                }

                //If the connection timeout is not set for this alias then 
                //set it to 10 seconds
                if (tConnectTimeout <= 0) {
                    tConnectTimeout = 10;
                    System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '"
                            + tAlias + "' using 10 seconds");
                }

                //Make sure another alias with the same name is not already 
                //defined in the config
                if (dbPools.containsKey(tAlias)) {
                    throw new Exception(
                            "the alias '" + tAlias + "' is already defined in " + " the provided config file");
                }

                //Everything is nicely set! Lets add a connection pool to the 
                //dbPool Hashtable keyed by this alias name
                dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections,
                        tExpirationTime, tConnectTimeout, tAlias));
            }
        }

        loadClusters: {
            final JSONArray tClusters = jObj.optJSONArray("clusters");

            if (tClusters != null) {
                for (int c = 0; c < tClusters.length(); c++) {
                    final JSONObject tObj = tClusters.getJSONObject(c);
                    final String tAlias = tObj.getString("alias");
                    final String tWriteTo = tObj.getString("writeTo");

                    if (dbPools.containsKey(tAlias)) {
                        throw new Exception("the alias '" + tAlias + "' is already defined.");
                    }

                    if (!dbPools.containsKey(tWriteTo)) {
                        throw new Exception(
                                "the alias '" + tWriteTo + "' is not present in the valid dbAliases. "
                                        + "This alias cannot be used for a cluster.");
                    }

                    //Add the dbAlias to the cluster writeTo list
                    ConnectionPool writeTo = dbPools.get(tWriteTo);

                    final JSONArray tReadFrom = tObj.getJSONArray("readFrom");
                    ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>();
                    for (int r = 0; r < tReadFrom.length(); r++) {
                        final String tRead = tReadFrom.getString(r);
                        if (!dbPools.containsKey(tRead)) {
                            throw new Exception(
                                    "the alias '" + tRead + "' is not present in the valid dbAliases. "
                                            + "This alias cannot be used for a cluster.");
                        }
                        //Add the dbAlias to the cluster readFrom list
                        readFromList.add(dbPools.get(tRead));
                    }

                    dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList));
                }
            }
        }

        server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools);

    } catch (Exception jsonEx) {
        System.out.println("DBMojoServer: Config error, " + jsonEx);
        System.exit(-1);
    }

    return server;
}

From source file:org.telegram.android.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }//  w w w.  ja va2s. co m
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>();
    final HashMap<Long, TLRPC.WebPage> webPages = new HashMap<>();
    final ArrayList<MessageObject> pushMessages = new ArrayList<>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadMessagesInbox = new HashMap<>();
    final HashMap<Integer, Integer> markAsReadMessagesOutbox = new HashMap<>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<>();
    final ArrayList<Integer> deletedMessages = new ArrayList<>();
    boolean printChanged = false;
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<>();
    final ArrayList<Integer> contactsIds = new ArrayList<>();

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                putUsers(usersArr, false);
                putChats(chatsArr, false);
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                TLRPC.User user = getUser(upd.message.from_id);
                if (usersDict.get(upd.message.from_id) == null && user == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && getChat(upd.message.to_id.chat_id) == null) {
                    return false;
                }

                if (user != null && user.status != null && user.status.expires <= 0) {
                    onlinePrivacy.put(upd.message.from_id, ConnectionsManager.getInstance().getCurrentTime());
                    interfaceUpdateMask |= UPDATE_MASK_STATUS;
                }
            }
            messagesArr.add(upd.message);
            ImageLoader.saveMessageThumbs(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict, true);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.getClientUserId()) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            if (!obj.isOut() && obj.isUnread()) {
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateReadMessagesContents) {
            markAsReadMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateReadHistoryInbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryInbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesInbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesInbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateReadHistoryOutbox) {
            TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryOutbox) update).peer;
            if (peer.chat_id != 0) {
                markAsReadMessagesOutbox.put(-peer.chat_id, update.max_id);
            } else {
                markAsReadMessagesOutbox.put(peer.user_id, update.max_id);
            }
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.getClientUserId()) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (update.action instanceof TLRPC.TL_sendMessageCancelAction) {
                    if (arr != null) {
                        for (int a = 0; a < arr.size(); a++) {
                            PrintingUser pu = arr.get(a);
                            if (pu.userId == update.user_id) {
                                arr.remove(a);
                                printChanged = true;
                                break;
                            }
                        }
                        if (arr.isEmpty()) {
                            printingUsers.remove(uid);
                        }
                    }
                } else {
                    if (arr == null) {
                        arr = new ArrayList<>();
                        printingUsers.put(uid, arr);
                    }
                    boolean exist = false;
                    for (PrintingUser u : arr) {
                        if (u.userId == update.user_id) {
                            exist = true;
                            u.lastTime = currentTime;
                            u.action = update.action;
                            break;
                        }
                    }
                    if (!exist) {
                        PrintingUser newUser = new PrintingUser();
                        newUser.userId = update.user_id;
                        newUser.lastTime = currentTime;
                        newUser.action = update.action;
                        arr.add(newUser);
                        printChanged = true;
                    }
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.getInstance().clearUserPhotos(update.user_id);
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhone) {
            interfaceUpdateMask |= UPDATE_MASK_PHONE;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.getClientUserId();
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict, true);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                pushMessages.add(obj);
            }
        } else if (update instanceof TLRPC.TL_updateContactLink) {
            if (update.my_link instanceof TLRPC.TL_contactLinkContact) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.newSessionReceived);
                }
            });
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = update.date;
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper.getInstance()
                    .decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (decryptedMessages != null && !decryptedMessages.isEmpty()) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(uid, arr);
                }
                for (TLRPC.Message message : decryptedMessages) {
                    ImageLoader.saveMessageThumbs(message);
                    messagesArr.add(message);
                    MessageObject obj = new MessageObject(message, usersDict, true);
                    arr.add(obj);
                    pushMessages.add(obj);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id);
            if (encryptedChat != null) {
                update.user_id = encryptedChat.user_id;
                long uid = ((long) update.chat_id) << 32;
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        u.action = new TLRPC.TL_sendMessageTypingAction();
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    newUser.action = new TLRPC.TL_sendMessageTypingAction();
                    arr.add(newUser);
                    printChanged = true;
                }
                onlinePrivacy.put(update.user_id, ConnectionsManager.getInstance().getCurrentTime());
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, false,
                    update.inviter_id, update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, true, 0,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.getInstance().updateDcSettings(0);
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            SecretChatHelper.getInstance().processUpdateEncryption((TLRPC.TL_updateEncryption) update,
                    usersDict);
        } else if (update instanceof TLRPC.TL_updateUserBlocked) {
            final TLRPC.TL_updateUserBlocked finalUpdate = (TLRPC.TL_updateUserBlocked) update;
            if (finalUpdate.blocked) {
                ArrayList<Integer> ids = new ArrayList<>();
                ids.add(finalUpdate.user_id);
                MessagesStorage.getInstance().putBlockedUsers(ids, false);
            } else {
                MessagesStorage.getInstance().deleteBlockedUser(finalUpdate.user_id);
            }
            MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                @Override
                public void run() {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (finalUpdate.blocked) {
                                if (!blockedUsers.contains(finalUpdate.user_id)) {
                                    blockedUsers.add(finalUpdate.user_id);
                                }
                            } else {
                                blockedUsers.remove((Integer) finalUpdate.user_id);
                            }
                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.blockedUsersDidLoaded);
                        }
                    });
                }
            });
        } else if (update instanceof TLRPC.TL_updateNotifySettings) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateServiceNotification) {
            TLRPC.TL_message newMessage = new TLRPC.TL_message();
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.flags = TLRPC.MESSAGE_FLAG_UNREAD;
            newMessage.date = ConnectionsManager.getInstance().getCurrentTime();
            newMessage.from_id = 777000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.getClientUserId();
            newMessage.dialog_id = 777000;
            newMessage.media = update.media;
            newMessage.message = ((TLRPC.TL_updateServiceNotification) update).message;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict, true);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            pushMessages.add(obj);
        } else if (update instanceof TLRPC.TL_updatePrivacy) {
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateWebPage) {
            webPages.put(update.webpage.id, update.webpage);
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            if (updatePrintingUsersWithNewMessages(key, value)) {
                printChanged = true;
            }
        }
    }

    if (printChanged) {
        updatePrintingStrings();
    }

    final int interfaceUpdateMaskFinal = interfaceUpdateMask;
    final boolean printChangedArg = printChanged;

    if (!contactsIds.isEmpty()) {
        ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict);
    }

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (!pushMessages.isEmpty()) {
                        NotificationsController.getInstance().processNewMessages(pushMessages, true);
                    }
                }
            });
        }
    });

    if (!messagesArr.isEmpty()) {
        MessagesStorage.getInstance().putMessages(messagesArr, true, true, false,
                MediaController.getInstance().getAutodownloadMask());
    }

    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            int updateMask = interfaceUpdateMaskFinal;

            boolean avatarsUpdate = false;
            if (!updatesOnMainThread.isEmpty()) {
                ArrayList<TLRPC.User> dbUsers = new ArrayList<>();
                ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
                SharedPreferences.Editor editor = null;
                for (TLRPC.Update update : updatesOnMainThread) {
                    final TLRPC.User toDbUser = new TLRPC.User();
                    toDbUser.id = update.user_id;
                    final TLRPC.User currentUser = getUser(update.user_id);
                    if (update instanceof TLRPC.TL_updatePrivacy) {
                        if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) {
                            ContactsController.getInstance().setPrivacyRules(update.rules);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserStatus) {
                        if (update.status instanceof TLRPC.TL_userStatusRecently) {
                            update.status.expires = -100;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastWeek) {
                            update.status.expires = -101;
                        } else if (update.status instanceof TLRPC.TL_userStatusLastMonth) {
                            update.status.expires = -102;
                        }
                        if (currentUser != null) {
                            currentUser.id = update.user_id;
                            currentUser.status = update.status;
                        }
                        toDbUser.status = update.status;
                        dbUsersStatus.add(toDbUser);
                        if (update.user_id == UserConfig.getClientUserId()) {
                            NotificationsController.getInstance()
                                    .setLastOnlineFromOtherDevice(update.status.expires);
                        }
                    } else if (update instanceof TLRPC.TL_updateUserName) {
                        if (currentUser != null) {
                            if (!(currentUser instanceof TLRPC.TL_userContact)) {
                                currentUser.first_name = update.first_name;
                                currentUser.last_name = update.last_name;
                            }
                            if (currentUser.username != null && currentUser.username.length() > 0) {
                                usersByUsernames.remove(currentUser.username);
                            }
                            if (update.username != null && update.username.length() > 0) {
                                usersByUsernames.put(update.username, currentUser);
                            }
                            currentUser.username = update.username;
                        }
                        toDbUser.first_name = update.first_name;
                        toDbUser.last_name = update.last_name;
                        toDbUser.username = update.username;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhoto) {
                        if (currentUser != null) {
                            currentUser.photo = update.photo;
                        }
                        avatarsUpdate = true;
                        toDbUser.photo = update.photo;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateUserPhone) {
                        if (currentUser != null) {
                            currentUser.phone = update.phone;
                            Utilities.phoneBookQueue.postRunnable(new Runnable() {
                                @Override
                                public void run() {
                                    ContactsController.getInstance().addContactToPhoneBook(currentUser, true);
                                }
                            });
                        }
                        toDbUser.phone = update.phone;
                        dbUsers.add(toDbUser);
                    } else if (update instanceof TLRPC.TL_updateNotifySettings) {
                        if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings
                                && update.peer instanceof TLRPC.TL_notifyPeer) {
                            if (editor == null) {
                                SharedPreferences preferences = ApplicationLoader.applicationContext
                                        .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                                editor = preferences.edit();
                            }
                            long dialog_id = update.peer.peer.user_id;
                            if (dialog_id == 0) {
                                dialog_id = -update.peer.peer.chat_id;
                            }
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                dialog.notify_settings = update.notify_settings;
                            }
                            if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                    .getCurrentTime()) {
                                int until = 0;
                                if (update.notify_settings.mute_until > ConnectionsManager.getInstance()
                                        .getCurrentTime() + 60 * 60 * 24 * 365) {
                                    editor.putInt("notify2_" + dialog_id, 2);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = Integer.MAX_VALUE;
                                    }
                                } else {
                                    until = update.notify_settings.mute_until;
                                    editor.putInt("notify2_" + dialog_id, 3);
                                    editor.putInt("notifyuntil_" + dialog_id,
                                            update.notify_settings.mute_until);
                                    if (dialog != null) {
                                        dialog.notify_settings.mute_until = until;
                                    }
                                }
                                MessagesStorage.getInstance().setDialogFlags(dialog_id,
                                        ((long) until << 32) | 1);
                            } else {
                                if (dialog != null) {
                                    dialog.notify_settings.mute_until = 0;
                                }
                                editor.remove("notify2_" + dialog_id);
                                MessagesStorage.getInstance().setDialogFlags(dialog_id, 0);
                            }

                        } /* else if (update.peer instanceof TLRPC.TL_notifyChats) { disable global settings sync
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableGroup", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews);
                          } else if (update.peer instanceof TLRPC.TL_notifyUsers) {
                          if (editor == null) {
                              SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                              editor = preferences.edit();
                          }
                          editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0);
                          editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews);
                          }*/
                    }
                }
                if (editor != null) {
                    editor.commit();
                    NotificationCenter.getInstance()
                            .postNotificationName(NotificationCenter.notificationsSettingsUpdated);
                }
                MessagesStorage.getInstance().updateUsers(dbUsersStatus, true, true, true);
                MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true);
            }

            if (!webPages.isEmpty()) {
                NotificationCenter.getInstance()
                        .postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPages);
            }

            if (!messages.isEmpty()) {
                for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                    Long key = entry.getKey();
                    ArrayList<MessageObject> value = entry.getValue();
                    updateInterfaceWithMessages(key, value);
                }
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
            }
            if (printChangedArg) {
                updateMask |= UPDATE_MASK_USER_PRINT;
            }
            if (!contactsIds.isEmpty()) {
                updateMask |= UPDATE_MASK_NAME;
                updateMask |= UPDATE_MASK_USER_PHONE;
            }
            if (!chatInfoToUpdate.isEmpty()) {
                for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
                    MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
                    NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded,
                            info.chat_id, info);
                }
            }
            if (updateMask != 0) {
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces,
                        updateMask);
            }
        }
    });

    MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
        @Override
        public void run() {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    int updateMask = 0;
                    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead,
                                markAsReadMessagesInbox, markAsReadMessagesOutbox);
                        NotificationsController.getInstance().processReadMessages(markAsReadMessagesInbox, 0, 0,
                                0, false);
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesInbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadMessagesOutbox.entrySet()) {
                            TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
                            if (dialog != null && dialog.top_message <= entry.getValue()) {
                                MessageObject obj = dialogMessage.get(dialog.top_message);
                                if (obj != null) {
                                    obj.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadEncrypted.isEmpty()) {
                        for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                            NotificationCenter.getInstance().postNotificationName(
                                    NotificationCenter.messagesReadEncrypted, entry.getKey(), entry.getValue());
                            long dialog_id = (long) (entry.getKey()) << 32;
                            TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                            if (dialog != null) {
                                MessageObject message = dialogMessage.get(dialog.top_message);
                                if (message != null && message.messageOwner.date <= entry.getValue()) {
                                    message.setIsRead();
                                    updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                                }
                            }
                        }
                    }
                    if (!markAsReadMessages.isEmpty()) {
                        NotificationCenter.getInstance().postNotificationName(
                                NotificationCenter.messagesReadContent, markAsReadMessages);
                    }
                    if (!deletedMessages.isEmpty()) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.messagesDeleted, deletedMessages);
                        for (Integer id : deletedMessages) {
                            MessageObject obj = dialogMessage.get(id);
                            if (obj != null) {
                                obj.deleted = true;
                            }
                        }
                    }
                    if (updateMask != 0) {
                        NotificationCenter.getInstance()
                                .postNotificationName(NotificationCenter.updateInterfaces, updateMask);
                    }
                }
            });
        }
    });

    if (!webPages.isEmpty()) {
        MessagesStorage.getInstance().putWebPages(webPages);
    }
    if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()
            || !markAsReadEncrypted.isEmpty()) {
        if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
            MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true);
        }
        MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox,
                markAsReadEncrypted, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesContentAsRead(markAsReadMessages);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.getInstance().updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.getInstance().createTaskForSecretChat(update.chat_id, update.max_date, update.date,
                    1, null);
        }
    }

    return true;
}

From source file:org.telegram.messenger.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }/*from   ww  w.  ja  va 2 s  .c  o  m*/
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<Long, ArrayList<MessageObject>>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<TLRPC.Message>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<Integer>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<Integer, Integer>();
    final ArrayList<Integer> deletedMessages = new ArrayList<Integer>();
    final ArrayList<Long> printChanges = new ArrayList<Long>();
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<TLRPC.ChatParticipants>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<TLRPC.Update>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<TLRPC.TL_updateEncryptedMessagesRead>();
    final ArrayList<Integer> contactsIds = new ArrayList<Integer>();
    MessageObject lastMessage = null;

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<Integer, TLRPC.User>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<Integer, TLRPC.Chat>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (usersArr != null) {
                    for (TLRPC.User user : usersArr) {
                        users.put(user.id, user);
                        if (user.id == UserConfig.clientUserId) {
                            UserConfig.currentUser = user;
                        }
                    }
                }
                if (chatsArr != null) {
                    for (TLRPC.Chat chat : chatsArr) {
                        chats.put(chat.id, chat);
                    }
                }
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                if (usersDict.get(upd.message.from_id) == null && users.get(upd.message.from_id) == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && chats.get(upd.message.to_id.chat_id) == null) {
                    return false;
                }
            }
            messagesArr.add(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.clientUserId) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            MessagesStorage.lastPtsValue = update.pts;
            if (upd.message.from_id != UserConfig.clientUserId && upd.message.to_id != null) {
                if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateMessageID) {
            //can't be here
        } else if (update instanceof TLRPC.TL_updateReadMessages) {
            markAsReadMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateRestoreMessages) {
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.clientUserId) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<PrintingUser>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    arr.add(newUser);
                    if (!printChanges.contains(uid)) {
                        printChanges.add(uid);
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.Instance.clearUserPhotos(update.user_id);
            /*if (!(update.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { DEPRECATED
            if (usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserUpdatedPhoto();
                newMessage.action.newUserPhoto = update.photo;
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;
                    
                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
             }*/

            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
            //                if (!contactsIds.contains(update.user_id)) {
            //                    contactsIds.add(update.user_id);
            //                }
        } else if (update instanceof TLRPC.TL_updateContactLink) {
            if (update.my_link instanceof TLRPC.TL_contacts_myLinkContact
                    || update.my_link instanceof TLRPC.TL_contacts_myLinkRequested && update.my_link.contact) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateActivation) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.unread = true;
            newMessage.date = update.date;
            newMessage.from_id = 333000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.clientUserId;
            newMessage.out = false;
            newMessage.dialog_id = 333000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            MessagesStorage.lastQtsValue = update.qts;
            TLRPC.Message message = decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (message != null) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                messagesArr.add(message);
                MessageObject obj = new MessageObject(message, usersDict);
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(uid, arr);
                }
                arr.add(obj);
                if (message.from_id != UserConfig.clientUserId && message.to_id != null) {
                    if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            long uid = ((long) update.chat_id) << 32;
            ArrayList<PrintingUser> arr = printingUsers.get(uid);
            if (arr == null) {
                arr = new ArrayList<PrintingUser>();
                printingUsers.put(uid, arr);
            }
            boolean exist = false;
            for (PrintingUser u : arr) {
                if (u.userId == update.user_id) {
                    exist = true;
                    u.lastTime = currentTime;
                    break;
                }
            }
            if (!exist) {
                PrintingUser newUser = new PrintingUser();
                newUser.userId = update.user_id;
                newUser.lastTime = currentTime;
                arr.add(newUser);
                if (!printChanges.contains(uid)) {
                    printChanges.add(uid);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, false, update.inviter_id,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, true, 0, update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.Instance.updateDcSettings();
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            final TLRPC.EncryptedChat newChat = update.chat;
            long dialog_id = ((long) newChat.id) << 32;
            TLRPC.EncryptedChat existingChat = encryptedChats.get(newChat.id);
            if (existingChat == null) {
                Semaphore semaphore = new Semaphore(0);
                ArrayList<TLObject> result = new ArrayList<TLObject>();
                MessagesStorage.Instance.getEncryptedChat(newChat.id, semaphore, result);
                try {
                    semaphore.acquire();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                if (result.size() == 2) {
                    existingChat = (TLRPC.EncryptedChat) result.get(0);
                    TLRPC.User user = (TLRPC.User) result.get(1);
                    users.putIfAbsent(user.id, user);
                }
            }

            if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) {
                int user_id = newChat.participant_id;
                if (user_id == UserConfig.clientUserId) {
                    user_id = newChat.admin_id;
                }
                TLRPC.User user = users.get(user_id);
                if (user == null) {
                    user = usersDict.get(user_id);
                }
                newChat.user_id = user_id;
                final TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                dialog.id = dialog_id;
                dialog.unread_count = 0;
                dialog.top_message = 0;
                dialog.last_message_date = update.date;

                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        dialogs_dict.put(dialog.id, dialog);
                        dialogs.add(dialog);
                        dialogsServerOnly.clear();
                        encryptedChats.put(newChat.id, newChat);
                        Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                            @Override
                            public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {
                                if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                    return 0;
                                } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                    return 1;
                                } else {
                                    return -1;
                                }
                            }
                        });
                        for (TLRPC.TL_dialog d : dialogs) {
                            if ((int) d.id != 0) {
                                dialogsServerOnly.add(d);
                            }
                        }
                        NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                    }
                });
                MessagesStorage.Instance.putEncryptedChat(newChat, user, dialog);
                acceptSecretChat(newChat);
            } else if (newChat instanceof TLRPC.TL_encryptedChat) {
                if (existingChat != null && existingChat instanceof TLRPC.TL_encryptedChatWaiting
                        && (existingChat.auth_key == null || existingChat.auth_key.length == 1)) {
                    newChat.a_or_b = existingChat.a_or_b;
                    newChat.user_id = existingChat.user_id;
                    processAcceptedSecretChat(newChat);
                }
            } else {
                final TLRPC.EncryptedChat exist = existingChat;
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (exist != null) {
                            newChat.user_id = exist.user_id;
                            newChat.auth_key = exist.auth_key;
                            encryptedChats.put(newChat.id, newChat);
                        }
                        MessagesStorage.Instance.updateEncryptedChat(newChat);
                        NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, newChat);
                    }
                });
            }
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            boolean printChanged = updatePrintingUsersWithNewMessages(key, value);
            if (printChanged && !printChanges.contains(key)) {
                printChanges.add(key);
            }
        }
    }

    if (!printChanges.isEmpty()) {
        updatePrintingStrings();
    }

    final MessageObject lastMessageArg = lastMessage;
    final int interfaceUpdateMaskFinal = interfaceUpdateMask;

    if (!contactsIds.isEmpty()) {
        ContactsController.Instance.processContactsUpdates(contactsIds, usersDict);
    }

    if (!messagesArr.isEmpty()) {
        MessagesStorage.Instance.putMessages(messagesArr, true, true);
    }

    if (!messages.isEmpty() || !markAsReadMessages.isEmpty() || !deletedMessages.isEmpty()
            || !printChanges.isEmpty() || !chatInfoToUpdate.isEmpty() || !updatesOnMainThread.isEmpty()
            || !markAsReadEncrypted.isEmpty() || !contactsIds.isEmpty()) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                int updateMask = interfaceUpdateMaskFinal;

                boolean avatarsUpdate = false;
                if (!updatesOnMainThread.isEmpty()) {
                    ArrayList<TLRPC.User> dbUsers = new ArrayList<TLRPC.User>();
                    ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<TLRPC.User>();
                    for (TLRPC.Update update : updatesOnMainThread) {
                        TLRPC.User toDbUser = new TLRPC.User();
                        toDbUser.id = update.user_id;
                        TLRPC.User currentUser = users.get(update.user_id);
                        if (update instanceof TLRPC.TL_updateUserStatus) {
                            if (!(update.status instanceof TLRPC.TL_userStatusEmpty)) {
                                if (currentUser != null) {
                                    currentUser.id = update.user_id;
                                    currentUser.status = update.status;
                                    if (update.status instanceof TLRPC.TL_userStatusOnline) {
                                        currentUser.status.was_online = update.status.expires;
                                    } else if (update.status instanceof TLRPC.TL_userStatusOffline) {
                                        currentUser.status.expires = update.status.was_online;
                                    } else {
                                        currentUser.status.was_online = 0;
                                        currentUser.status.expires = 0;
                                    }
                                }
                                toDbUser.status = update.status;
                                dbUsersStatus.add(toDbUser);
                            }
                        } else if (update instanceof TLRPC.TL_updateUserName) {
                            if (currentUser != null) {
                                currentUser.first_name = update.first_name;
                                currentUser.last_name = update.last_name;
                            }
                            toDbUser.first_name = update.first_name;
                            toDbUser.last_name = update.last_name;
                            dbUsers.add(toDbUser);
                        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
                            if (currentUser != null) {
                                currentUser.photo = update.photo;
                            }
                            avatarsUpdate = true;
                            toDbUser.photo = update.photo;
                            dbUsers.add(toDbUser);
                        }
                    }
                    MessagesStorage.Instance.updateUsers(dbUsersStatus, true, true, true);
                    MessagesStorage.Instance.updateUsers(dbUsers, false, true, true);
                }

                if (!messages.isEmpty()) {
                    for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                        Long key = entry.getKey();
                        ArrayList<MessageObject> value = entry.getValue();
                        updateInterfaceWithMessages(key, value);
                    }
                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                }
                if (!markAsReadMessages.isEmpty()) {
                    for (Integer id : markAsReadMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.messageOwner.unread = false;
                        }
                    }
                    NotificationCenter.Instance.postNotificationName(messagesReaded, markAsReadMessages);
                }
                if (!markAsReadEncrypted.isEmpty()) {
                    for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                        NotificationCenter.Instance.postNotificationName(messagesReadedEncrypted,
                                entry.getKey(), entry.getValue());
                        long dialog_id = (long) (entry.getKey()) << 32;
                        TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                        if (dialog != null) {
                            MessageObject message = dialogMessage.get(dialog.top_message);
                            if (message != null && message.messageOwner.date <= entry.getValue()) {
                                message.messageOwner.unread = false;
                            }
                        }
                    }
                }
                if (!deletedMessages.isEmpty()) {
                    NotificationCenter.Instance.postNotificationName(messagesDeleted, deletedMessages);
                    for (Integer id : deletedMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.deleted = true;
                        }
                    }
                }
                if (!printChanges.isEmpty()) {
                    updateMask |= UPDATE_MASK_USER_PRINT;
                }
                if (!contactsIds.isEmpty()) {
                    updateMask |= UPDATE_MASK_NAME;
                    updateMask |= UPDATE_MASK_USER_PHONE;
                }
                if (!chatInfoToUpdate.isEmpty()) {
                    for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
                        MessagesStorage.Instance.updateChatInfo(info.chat_id, info, true);
                        NotificationCenter.Instance.postNotificationName(chatInfoDidLoaded, info.chat_id, info);
                    }
                }
                if (updateMask != 0) {
                    NotificationCenter.Instance.postNotificationName(updateInterfaces, updateMask);
                }
                if (lastMessageArg != null) {
                    showInAppNotification(lastMessageArg);
                }
            }
        });
    }

    if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsRead(markAsReadMessages, markAsReadEncrypted, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithReadedMessages(markAsReadMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.Instance.createTaskForDate(update.chat_id, update.max_date, update.date, 1);
        }
    }

    return true;
}