Example usage for java.util.concurrent ConcurrentHashMap get

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

Introduction

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

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:structuredPredictionNLG.SFX.java

/**
 * During this method, we calculate the alignments (naive or random), the language models, the available content and word actions, and finally the feature vectors.
 *//*from  ww w  .ja  v  a  2s.com*/
@Override
public void createTrainingData() {
    //setTrainingData(new ArrayList<>(getTrainingData().subList(0, 50)));
    //setTestingData(new ArrayList<>(getTrainingData()));

    // Calculate alignments between the word of the sentence and the atribute/values
    if (getUseAlignments().equals("naive")) {
        createNaiveAlignments(getTrainingData());
    } else {
        createRandomAlignments(getTrainingData());
    }

    // Create (or load from cache) the content and word language models per predicate
    if (isResetStoredCaches() || !loadLMs()) {
        HashMap<String, ArrayList<ArrayList<String>>> LMWordTrainingPerPred = new HashMap<>();
        HashMap<String, ArrayList<ArrayList<String>>> LMAttrTrainingPerPred = new HashMap<>();
        getTrainingData().stream().map((di) -> {
            if (!LMWordTrainingPerPred.containsKey(di.getMeaningRepresentation().getPredicate())) {
                LMWordTrainingPerPred.put(di.getMeaningRepresentation().getPredicate(),
                        new ArrayList<ArrayList<String>>());
                LMAttrTrainingPerPred.put(di.getMeaningRepresentation().getPredicate(),
                        new ArrayList<ArrayList<String>>());
            }
            return di;
        }).forEachOrdered((di) -> {
            HashSet<ArrayList<Action>> seqs = new HashSet<>();
            seqs.add(di.getDirectReferenceSequence());
            seqs.forEach((seq) -> {
                ArrayList<String> wordSeq = new ArrayList<>();
                ArrayList<String> attrSeq = new ArrayList<>();

                // We add some empty tokens at the start of each sequence
                wordSeq.add("@@");
                wordSeq.add("@@");
                attrSeq.add("@@");
                attrSeq.add("@@");
                for (int i = 0; i < seq.size(); i++) {
                    if (!seq.get(i).getAttribute().equals(Action.TOKEN_END)
                            && !seq.get(i).getWord().equals(Action.TOKEN_END)) {
                        wordSeq.add(seq.get(i).getWord());
                    }
                    if (attrSeq.isEmpty()) {
                        attrSeq.add(seq.get(i).getAttribute());
                    } else if (!attrSeq.get(attrSeq.size() - 1).equals(seq.get(i).getAttribute())) {
                        attrSeq.add(seq.get(i).getAttribute());
                    }
                }
                wordSeq.add(Action.TOKEN_END);
                LMWordTrainingPerPred.get(di.getMeaningRepresentation().getPredicate()).add(wordSeq);
                LMAttrTrainingPerPred.get(di.getMeaningRepresentation().getPredicate()).add(attrSeq);
            });
        });

        setWordLMsPerPredicate(new HashMap<>());
        setContentLMsPerPredicate(new HashMap<>());
        LMWordTrainingPerPred.keySet().stream().map((pred) -> {
            SimpleLM simpleWordLM = new SimpleLM(3);
            simpleWordLM.trainOnStrings(LMWordTrainingPerPred.get(pred));
            getWordLMsPerPredicate().put(pred, simpleWordLM);
            return pred;
        }).forEachOrdered((pred) -> {
            SimpleLM simpleAttrLM = new SimpleLM(3);
            simpleAttrLM.trainOnStrings(LMAttrTrainingPerPred.get(pred));
            getContentLMsPerPredicate().put(pred, simpleAttrLM);
        });
        writeLMs();
    }

    // Go through the sequences in the data and populate the available content and word action dictionaries
    // We populate a distinct word dictionary for each attribute, and populate it with the words of word sequences whose corresponding content sequences contain that attribute
    HashMap<String, HashSet<String>> availableContentActions = new HashMap<>();
    HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions = new HashMap<>();
    getTrainingData().forEach((DI) -> {
        String predicate = DI.getMeaningRepresentation().getPredicate();
        if (!availableContentActions.containsKey(predicate)) {
            availableContentActions.put(predicate, new HashSet<String>());
            availableContentActions.get(predicate).add(Action.TOKEN_END);
        }
        if (!availableWordActions.containsKey(predicate)) {
            availableWordActions.put(predicate, new HashMap<String, HashSet<Action>>());
        }
        ArrayList<Action> realization = DI.getDirectReferenceSequence();
        realization.stream().filter((a) -> (!a.getAttribute().equals(Action.TOKEN_END)))
                .forEachOrdered((Action a) -> {
                    String attr;
                    if (a.getAttribute().contains("=")) {
                        attr = a.getAttribute().substring(0, a.getAttribute().indexOf('='));
                    } else {
                        attr = a.getAttribute();
                    }
                    availableContentActions.get(predicate).add(attr);
                    if (!availableWordActions.get(predicate).containsKey(attr)) {
                        availableWordActions.get(predicate).put(attr, new HashSet<Action>());
                        availableWordActions.get(predicate).get(attr).add(new Action(Action.TOKEN_END, attr));
                    }
                    if (!a.getWord().equals(Action.TOKEN_START) && !a.getWord().equals(Action.TOKEN_END)
                            && !a.getWord().matches("([,.?!;:'])")) {
                        if (a.getWord().startsWith(Action.TOKEN_X)) {
                            if (a.getWord().substring(3, a.getWord().lastIndexOf('_')).toLowerCase().trim()
                                    .equals(attr)) {
                                availableWordActions.get(predicate).get(attr)
                                        .add(new Action(a.getWord(), attr));
                            }
                        } else {
                            availableWordActions.get(predicate).get(attr).add(new Action(a.getWord(), attr));
                        }
                    }
                });
    });
    setAvailableContentActions(availableContentActions);
    setAvailableWordActions(availableWordActions);

    //When using random alignments we do not consider the value alignments either
    if (getUseAlignments().equals("random")) {
        setValueAlignments(new HashMap<>());
    }

    // Infer the feature vectors of the training data
    if (isResetStoredCaches() || !loadTrainingData(getTrainingData().size())) {
        System.out.print("Create training data...");
        Object[] results = inferFeatureAndCostVectors();
        System.out.print("almost...");

        @SuppressWarnings("unchecked")
        ConcurrentHashMap<DatasetInstance, HashMap<String, ArrayList<Instance>>> getPredicateContentTrainingDataBefore = (ConcurrentHashMap<DatasetInstance, HashMap<String, ArrayList<Instance>>>) results[0];
        @SuppressWarnings("unchecked")
        ConcurrentHashMap<DatasetInstance, HashMap<String, HashMap<String, ArrayList<Instance>>>> getPredicateWordTrainingDataBefore = (ConcurrentHashMap<DatasetInstance, HashMap<String, HashMap<String, ArrayList<Instance>>>>) results[1];

        // Reorganize the feature/cost vector collections 
        // Initially they are mapped according to DatasetInstance (since it helps with parallel processing) but we prefer them mapped by predicate for training
        setPredicateContentTrainingData(new HashMap<>());
        getTrainingData().forEach((di) -> {
            getPredicateContentTrainingDataBefore.get(di).keySet().stream().map((predicate) -> {
                if (!getPredicateContentTrainingData().containsKey(predicate)) {
                    getPredicateContentTrainingData().put(predicate, new ArrayList<Instance>());
                }
                return predicate;
            }).forEachOrdered((predicate) -> {
                getPredicateContentTrainingData().get(predicate)
                        .addAll(getPredicateContentTrainingDataBefore.get(di).get(predicate));
            });
        });
        setPredicateWordTrainingData(new HashMap<>());
        getTrainingData().forEach((di) -> {
            getPredicateWordTrainingDataBefore.get(di).keySet().stream().map((predicate) -> {
                if (!getPredicateWordTrainingData().containsKey(predicate)) {
                    getPredicateWordTrainingData().put(predicate, new HashMap<String, ArrayList<Instance>>());
                }
                return predicate;
            }).forEachOrdered((predicate) -> {
                getPredicateWordTrainingDataBefore.get(di).get(predicate).keySet().stream().map((attribute) -> {
                    if (!getPredicateWordTrainingData().get(predicate).containsKey(attribute)) {
                        getPredicateWordTrainingData().get(predicate).put(attribute, new ArrayList<Instance>());
                    }
                    return attribute;
                }).forEachOrdered((attribute) -> {
                    getPredicateWordTrainingData().get(predicate).get(attribute)
                            .addAll(getPredicateWordTrainingDataBefore.get(di).get(predicate).get(attribute));
                });
            });
        });
        writeTrainingData(getTrainingData().size());
    }
}

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;
    }//from   w  ww  .j av  a2s  . c  om
    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;
    }//  w w w .  java 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;
}

From source file:com.app.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;//from  w w w .  ja v  a  2  s.c o  m
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //log.info("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:com.web.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;//  w ww .ja v  a2 s  .  c  om
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //System.out.println(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //System.out.println(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //System.out.println("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //System.out.println("In read obect");
                                    object = ois.readObject();
                                    //System.out.println("Class Cast");
                                    //System.out.println("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //System.out.println("readObject");
                                    //System.out.println("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //System.out.println("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //System.out.println(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //System.out.println(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap
                                                .get(earServicesDirectory + "/" + serviceRegistry[0] + "/"
                                                        + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(jarservicesDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // System.out.println("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // System.out.println("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * System.out.println(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //System.out.println("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //System.out.println("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //System.out.println(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //System.out.println("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //System.out.println(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //System.out.println("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //System.out.println("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;

                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket("0.0.0.0",
                                            Integer.parseInt(nodesport[random.nextInt(nodesport.length)]));
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //System.out.println("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   System.out.println("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //System.out.println("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //System.out.println("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //System.out.println(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //System.out.println("In write1");
                                numberOfServicesRequests++;
                                //System.out.println("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {

                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static ConcurrentHashMap<Integer, HashSet<Integer>> loadCustomerWingInstances() {
    ConcurrentHashMap<Integer, HashSet<Integer>> instTable = new ConcurrentHashMap<Integer, HashSet<Integer>>();
    ResultSet rs = null;//from   ww  w  . ja v  a 2  s .c o  m
    try {
        rs = DBHelper.executeQuery("select * from customer_wing_instance");
        while (rs.next()) {
            int custId = rs.getInt("customer_id");
            int instId = rs.getInt("instance_id");
            HashSet<Integer> instances = instTable.get(custId);
            if (instances == null) {
                instances = new HashSet<Integer>();
                instTable.put(custId, instances);
            }
            instances.add(instId);

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
    }

    return instTable;
}

From source file:gov.noaa.pfel.coastwatch.Projects.java

/** Test various hashmap implementations. */
public static void testHashMaps() {
    String2.log("test regular HashMap");
    long time = System.currentTimeMillis();
    HashMap hashmap = new HashMap();
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        hashmap.put(s, s);// w  w w. j  a v  a  2  s  .  co m
    }
    String max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) hashmap.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("test regular hashMap finished longest=" + max + " time=" + (System.currentTimeMillis() - time)
            + "ms"); //282     

    //***
    String2.log("test synchronized HashMap");
    time = System.currentTimeMillis();
    Map smap = Collections.synchronizedMap(new HashMap());
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        smap.put(s, s);
    }
    max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) smap.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("test synchronized hashMap finished longest=" + max + " time="
            + (System.currentTimeMillis() - time) + "ms"); //343     

    //***
    String2.log("testConcurrentHashMap");
    time = System.currentTimeMillis();
    ConcurrentHashMap map = new ConcurrentHashMap(16, 0.75f, 4); //intentionally low initCapacity
    for (int i = 0; i < 1000; i++) {
        String s = "" + i;
        map.put(s, s);
    }
    max = "";
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 1000; j++) {
            String s = (String) map.get("" + j);
            max = s.length() > max.length() ? s : max;
        }
    }
    String2.log("testConcurrentHashMap finished longest=" + max + " time=" + (System.currentTimeMillis() - time)
            + "ms"); //282
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static void loadCustomerDeviceDetails(
        ConcurrentHashMap<Integer, HashMap<Integer, String>> customerDevice,
        ConcurrentHashMap<Integer, ConcurrentHashMap<String, Integer>> customerDeviceIPList) {
    ResultSet rs = null;/*from   w  ww  .java2 s . co m*/

    try {
        rs = DBHelper.executeQuery(
                "select * from customer_device where device_id  not in (select mod_id from nodes_modules)");
        while (rs.next()) {
            int custId = rs.getInt("customer_id");
            int deviceId = rs.getInt("device_id");
            NetworkNode node = NetworkNodeCache.getInstance().getNodeByID(deviceId);
            if (node == null) {
                continue;
            }
            node.setCustomerId(custId);
            // DeviceWeightageCache.getInstance().addCustNodeWeightageMap(custId,
            // node);
            HashMap<Integer, String> devices = customerDevice.get(custId);
            if (devices == null) {
                devices = new HashMap<Integer, String>();
                customerDevice.put(custId, devices);
            }

            devices.put(deviceId, "");

            ConcurrentHashMap<String, Integer> devicesIpList = customerDeviceIPList.get(custId);
            if (devicesIpList == null) {
                devicesIpList = new ConcurrentHashMap<String, Integer>();
                customerDeviceIPList.put(custId, devicesIpList);
            }
            devicesIpList.put(node.getIpAddr().toString(), deviceId);
            /*
             * Removing this code because we no longer worry about duplicate devices in NCCM. CSPC takes care of
             * this. We only put the device management IP address in this list now.
             */
            // ArrayList list = node.getAllInterfaces();
            // Iterator it = list.iterator();
            // while (it.hasNext())
            // {
            // NetworkInterface nif = (NetworkInterface) it.next();
            // if (nif.getIpAddress() != null)
            // {
            // devicesIpList.put(nif.getIpAddress(), deviceId);
            // }
            // }

        }

    } catch (Exception ee) {
        logger.warn("Error in loadCustomerDeviceDetails", ee);
    } finally {
        try {
            rs.close();
        } catch (Exception ee) {
        }
    }
}

From source file:com.app.server.EJBDeployer.java

public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) {
    try {//  w w w .  jav  a 2  s  .c  o  m
        Vector<EJBContext> ejbContexts = null;
        EJBContext ejbContext;
        log.info(url.toURI());
        ConcurrentHashMap<String, RARArchiveData> rardata = (ConcurrentHashMap<String, RARArchiveData>) mbeanServer
                .getAttribute(rarDeployerName, "RARArchiveDataAllAdapters");
        Collection<RARArchiveData> rarcls = rardata.values();
        Iterator<RARArchiveData> rarcl = rarcls.iterator();
        RARArchiveData rararcdata;

        FileObject filetoScan = manager.resolveFile("jar:" + url.toString() + "!/");
        HashSet<Class<?>>[] classes = new HashSet[] { new HashSet(), new HashSet(), new HashSet() };

        VFSClassLoader jarCL;

        if (cL != null) {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, cL);
        } else {
            jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager,
                    Thread.currentThread().getContextClassLoader());
        }
        Class[] annot = new Class[] { Stateless.class, Stateful.class, MessageDriven.class };
        scanJar(filetoScan, classes, annot, jarCL);
        Set<Class<?>> clsStateless = classes[0];
        Set<Class<?>> clsStateful = classes[1];
        Set<Class<?>> clsMessageDriven = classes[2];
        //System.gc();
        staticObjs = null;
        EJBContainer container = EJBContainer.getInstance(classes);
        container.inject();
        if (clsStateless.size() > 0) {
            staticObjs = new Vector<Object>();
            ejbContexts = new Vector<EJBContext>();
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            for (Class<?> ejbInterface : clsStateless) {
                BeanPool.getInstance().create(ejbInterface);
                obj = BeanPool.getInstance().get(ejbInterface);
                System.out.println(obj);
                ProxyFactory factory = new ProxyFactory();
                proxyobj = factory.createWithBean(obj);
                staticObjs.add(proxyobj);
                Object unicastobj = UnicastRemoteObject.exportObject((Remote) proxyobj, 0);
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + obj);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, (Remote) unicastobj);
                    ejbContext.put(remoteBinding, obj.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsStateful.size() > 0) {
            if (staticObjs == null) {
                staticObjs = new Vector<Object>();
            }
            if (ejbContexts == null) {
                ejbContexts = new Vector<EJBContext>();
            }
            ejbContext = new EJBContext();
            ejbContext.setJarPath(url.toString());
            ejbContext.setJarDeployed(url.toString());
            StatefulBeanObject statefulBeanObject = null;
            for (Class<?> ejbInterface : clsStateful) {
                BeanPool.getInstance().create(ejbInterface);
                obj1 = ejbInterface.newInstance();
                if (statefulBeanObject == null) {
                    statefulBeanObject = new StatefulBeanObject(obj1, url.toString());
                } else {
                    statefulBeanObject.addStatefulSessionBeanObject(obj1);
                }
                //System.out.println(obj1);
                staticObjs.add(statefulBeanObject);
                /*Object unicastobj1 = UnicastRemoteObject.exportObject(
                      (Remote) obj1,
                      0);*/
                String remoteBinding = container.getRemoteBinding(ejbInterface);
                System.out.println(remoteBinding + " for EJB" + statefulBeanObject);
                if (remoteBinding != null) {
                    // registry.unbind(remoteBinding);
                    ic.bind("java:/" + remoteBinding, statefulBeanObject);
                    ejbContext.put(remoteBinding, statefulBeanObject.getClass());
                    //registry.rebind(remoteBinding, (Remote)unicastobj1);
                }
                // registry.rebind("name", (Remote) obj);
            }
            ejbContexts.add(ejbContext);
            jarEJBMap.put(url.toString(), ejbContexts);
        }
        if (clsMessageDriven.size() > 0) {

            MDBContext mdbContext = null;
            ConcurrentHashMap<String, MDBContext> mdbContexts;
            if (jarMDBMap.get(url.toString()) != null) {
                mdbContexts = jarMDBMap.get(url.toString());
            } else {
                mdbContexts = new ConcurrentHashMap<String, MDBContext>();
            }
            jarMDBMap.put(url.toString(), mdbContexts);
            MDBContext mdbContextOld;
            for (Class<?> mdbBean : clsMessageDriven) {
                String classwithpackage = mdbBean.getName();
                //System.out.println("class package" + classwithpackage);
                classwithpackage = classwithpackage.replace("/", ".");
                //System.out.println("classList:"
                //   + classwithpackage.replace("/", "."));
                final Class mdbBeanCls = mdbBean;
                try {
                    if (!classwithpackage.contains("$")) {
                        // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        // System.out.println();
                        if (!mdbBean.isInterface()) {
                            Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                            if (classServicesAnnot != null) {
                                Adapter adapter = null;
                                ActivationConfigProperty[] activationConfigProp = null;
                                for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                    if (classServicesAnnot[annotcount] instanceof Adapter) {
                                        adapter = (Adapter) classServicesAnnot[annotcount];
                                    } else if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                        MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                        activationConfigProp = messageDrivenAnnot.activationConfig();
                                        mdbContext = new MDBContext();
                                        mdbContext.setMdbName(messageDrivenAnnot.name());
                                    }
                                }
                                if (adapter != null) {
                                    /*if(rarcl.hasNext()){
                                       rararcdata=rardata.get(rarDeployerName);
                                          rararcdata=rarcl.next();
                                          //classLoader = new VFSClassLoader(rararcdata.getVfsClassLoader().getFileObjects(),rararcdata.getFsManager(),classLoader);
                                          FileObject[] fileObjectArray=rararcdata.getVfsClassLoader().getFileObjects();
                                          //urlset.addAll(ClasspathHelper.forClassLoader(rararcdata.getVfsClassLoader()));
                                          for(FileObject fileObject:fileObjectArray){
                                             fileObjects.add(fileObject.getURL());
                                             //urlset.add(fileObject.getURL());
                                             //System.out.println(Vfs.fromURL(fileObject.getURL()).getFiles().iterator().next().getRelativePath());
                                          }
                                          classLoader = new URLClassLoader(fileObjects.toArray(new URL[fileObjects.size()]),Thread.currentThread().getContextClassLoader());
                                    }*/
                                    RARArchiveData rarArchiveData = (RARArchiveData) mbeanServer.invoke(
                                            rarDeployerName, "getRARArchiveData",
                                            new Object[] { adapter.adapterName() },
                                            new String[] { String.class.getName() });
                                    if (rarArchiveData == null)
                                        throw new Exception("RAR Adapter " + adapter.adapterName()
                                                + " Not found in deploy folder");
                                    Class resourceAdapterClass = rarArchiveData.getResourceAdapterClass();
                                    final ResourceAdapter resourceAdapter = (ResourceAdapter) resourceAdapterClass
                                            .newInstance();
                                    Class activationSpecClass = rarArchiveData.getActivationspecclass();
                                    final ActivationSpec activationSpec = (ActivationSpec) activationSpecClass
                                            .newInstance();
                                    Vector<ConfigProperty> configProperties = rarArchiveData.getConfigPropery();
                                    Integer configPropertyInteger;
                                    Long configPropertyLong;
                                    Boolean configPropertyBoolean;
                                    Method method;
                                    if (configProperties != null) {
                                        for (ConfigProperty configProperty : configProperties) {
                                            String property = configProperty.getConfigpropertyname();
                                            property = (property.charAt(0) + "").toUpperCase()
                                                    + property.substring(1);
                                            Class propertytype = Class
                                                    .forName(configProperty.getConfigpropertytype());
                                            try {

                                                method = activationSpecClass.getMethod("set" + property,
                                                        propertytype);
                                                if (propertytype == String.class) {
                                                    method.invoke(activationSpec,
                                                            configProperty.getConfigpropertyvalue());
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } else if (propertytype == Integer.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyInteger = new Integer(
                                                                configProperty.getConfigpropertyvalue());
                                                        try {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger);
                                                        } catch (Exception ex) {
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                        }
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Long.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyLong = new Long(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyLong);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                } else if (propertytype == Boolean.class) {
                                                    if (configProperty.getConfigpropertyvalue() != null
                                                            && !configProperty.getConfigpropertyvalue()
                                                                    .equalsIgnoreCase("")) {
                                                        configPropertyBoolean = new Boolean(
                                                                configProperty.getConfigpropertyvalue());
                                                        method.invoke(activationSpec, configPropertyBoolean);
                                                        ConfigResourceAdapter(resourceAdapterClass,
                                                                propertytype, resourceAdapter, property,
                                                                configProperty);
                                                    }
                                                }
                                            } catch (Exception ex) {
                                                try {
                                                    if (propertytype == Integer.class) {
                                                        method = activationSpecClass.getMethod("set" + property,
                                                                int.class);
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, int.class);
                                                            configPropertyInteger = new Integer(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyInteger.intValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);                                       
                                                        }
                                                    } else if (propertytype == Long.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, long.class);
                                                            configPropertyLong = new Long(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyLong.longValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    } else if (propertytype == Boolean.class) {
                                                        if (configProperty.getConfigpropertyvalue() != null
                                                                && !configProperty.getConfigpropertyvalue()
                                                                        .equalsIgnoreCase("")) {
                                                            method = activationSpecClass
                                                                    .getMethod("set" + property, boolean.class);
                                                            configPropertyBoolean = new Boolean(
                                                                    configProperty.getConfigpropertyvalue());
                                                            method.invoke(activationSpec,
                                                                    configPropertyBoolean.booleanValue());
                                                            //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty);
                                                        }
                                                    }
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                } catch (Exception ex1) {
                                                    ConfigResourceAdapter(resourceAdapterClass, propertytype,
                                                            resourceAdapter, property, configProperty);
                                                }
                                                //log.error("Could not set Configuration for rar activation spec", ex);
                                            }
                                        }
                                    }
                                    for (ActivationConfigProperty activationConfig : activationConfigProp) {
                                        String property = activationConfig.propertyName();
                                        property = (property.charAt(0) + "").toUpperCase()
                                                + property.substring(1);
                                        try {
                                            method = activationSpecClass.getMethod("set" + property,
                                                    String.class);
                                            method.invoke(activationSpec, activationConfig.propertyValue());
                                        } catch (Exception ex) {
                                            try {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            } catch (Exception ex1) {
                                                method = activationSpecClass.getMethod("set" + property,
                                                        Boolean.class);
                                                method.invoke(activationSpec,
                                                        new Boolean(activationConfig.propertyValue()));
                                            }
                                        }

                                    }
                                    final Class listenerClass = rarArchiveData.getMessagelistenertype();
                                    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
                                    Thread.currentThread()
                                            .setContextClassLoader(resourceAdapter.getClass().getClassLoader());
                                    resourceAdapter
                                            .start(new com.app.server.connector.impl.BootstrapContextImpl());
                                    MessageEndPointFactoryImpl messageEndPointFactoryImpl = new MessageEndPointFactoryImpl(
                                            listenerClass, mdbBeanCls.newInstance(), jarCL);
                                    resourceAdapter.endpointActivation(messageEndPointFactoryImpl,
                                            activationSpec);
                                    Thread.currentThread().setContextClassLoader(cCL);
                                    if (mdbContext != null) {
                                        mdbContext.setResourceAdapter(resourceAdapter);
                                        mdbContext.setMessageEndPointFactory(messageEndPointFactoryImpl);
                                        mdbContext.setActivationSpec(activationSpec);
                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                    }
                                    /*new Thread(){
                                       public void run(){
                                          try {
                                             resourceAdapter.endpointActivation(new com.app.server.connector.impl.MessageEndPointFactoryImpl(listenerClass, mdbBeanCls.newInstance(),raCl), activationSpec);
                                          } catch (
                                                Exception e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                                          }
                                       }
                                    }.start();*/

                                } else {
                                    for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                        if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                            MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                            ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                    .activationConfig();
                                            mdbContext = new MDBContext();
                                            mdbContext.setMdbName(messageDrivenAnnot.name());
                                            for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATIONTYPE)) {
                                                    mdbContext.setDestinationType(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.DESTINATION)) {
                                                    mdbContext.setDestination(
                                                            activationConfigProperty.propertyValue());
                                                } else if (activationConfigProperty.propertyName()
                                                        .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                    mdbContext.setAcknowledgeMode(
                                                            activationConfigProperty.propertyValue());
                                                }
                                            }
                                            if (mdbContext.getDestinationType().equals(Queue.class.getName())) {
                                                mdbContextOld = null;
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld != null && mdbContext.getDestination()
                                                            .equals(mdbContextOld.getDestination())) {
                                                        throw new Exception(
                                                                "Only one MDB can listen to destination:"
                                                                        + mdbContextOld.getDestination());
                                                    }
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Queue queue = (Queue) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(queue);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Queue=" + queue);
                                            } else if (mdbContext.getDestinationType()
                                                    .equals(Topic.class.getName())) {
                                                if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                    mdbContextOld = mdbContexts.get(mdbContext.getMdbName());
                                                    if (mdbContextOld.getConsumer() != null)
                                                        mdbContextOld.getConsumer().setMessageListener(null);
                                                    if (mdbContextOld.getSession() != null)
                                                        mdbContextOld.getSession().close();
                                                    if (mdbContextOld.getConnection() != null)
                                                        mdbContextOld.getConnection().close();
                                                }
                                                mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                Topic topic = (Topic) jms.lookup(mdbContext.getDestination());
                                                Connection connection = connectionFactory
                                                        .createConnection("guest", "guest");
                                                connection.start();
                                                Session session;
                                                if (mdbContext.getAcknowledgeMode() != null && mdbContext
                                                        .getAcknowledgeMode().equals("Auto-Acknowledge")) {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                } else {
                                                    session = connection.createSession(false,
                                                            Session.AUTO_ACKNOWLEDGE);
                                                }
                                                MessageConsumer consumer = session.createConsumer(topic);
                                                consumer.setMessageListener(
                                                        (MessageListener) mdbBean.newInstance());
                                                mdbContext.setConnection(connection);
                                                mdbContext.setSession(session);
                                                mdbContext.setConsumer(consumer);
                                                System.out.println("Topic=" + topic);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("Error : ", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }
        if (staticObjs != null) {
            staticObjsEjbMap.put(url.toString(), staticObjs);
        }
        this.jarsDeployed.add(url.toURI().toString());
        log.info(url.toString() + " Deployed");
    } catch (Exception ex) {
        log.error("Error in deploying the jar file: " + url, ex);
        //ex.printStackTrace();
    } finally {
        /*if(classLoader!=null){
           try {
              classLoader.close();
           } catch (Exception e) {
              log.error("error in closing the classloader", e);
              // TODO Auto-generated catch block
              //e.printStackTrace();
           }
           ClassLoaderUtil.closeClassLoader(classLoader);
        }*/
    }

}