List of usage examples for java.util.concurrent ConcurrentHashMap put
public V put(K key, V value)
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; }/* ww w.j a va2 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.web.server.EJBDeployer.java
@Override public void run() { EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap, jarMDBMap, jms, connectionFactory); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); FileObject listendir = null;/*from w w w . j a va 2 s . c om*/ StandardFileSystemManager fsManager = new StandardFileSystemManager(); String[] dirsToScan = scanDirectory.split(";"); EJBContext ejbContext; try { File scanDirFile = new File(dirsToScan[0]); File[] scanJarFiles = scanDirFile.listFiles(); System.out.println("SCANDIRECTORY=" + scanDirectory); if (scanJarFiles != null) { for (File scanJarFile : scanJarFiles) { if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) { URLClassLoader classLoader = new URLClassLoader( new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer .getInstance("file:///" + scanJarFile.getAbsolutePath(), config); container.inject(); Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (cls.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(scanJarFile.getAbsolutePath()); ejbContext.setJarDeployed(scanJarFile.getName()); for (Class<?> ejbInterface : cls) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) { mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"), 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("/", ".")); 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) { 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) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); System.out.println(scanJarFile.getAbsolutePath() + " Deployed"); } } } FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(1000); fm.start(); }
From source file:org.wso2.carbon.event.processor.core.internal.CarbonEventProcessorService.java
/** * Starts an execution plan runtime for the given (valid) execution plan. * * @param executionPlan Execution plan. It is assumed that the execution plan is a valid one when reaching this function. * @param isEditable whether the execution plan is editable. * @throws ExecutionPlanConfigurationException *///w w w . j av a 2 s .co m public void addExecutionPlan(String executionPlan, boolean isEditable) throws ExecutionPlanConfigurationException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); SiddhiManager siddhiManager = EventProcessorValueHolder.getSiddhiManager(); EventProcessorHelper.loadDataSourceConfiguration(siddhiManager); ExecutionPlanRuntime executionPlanRuntime = null; org.wso2.siddhi.query.api.ExecutionPlan parsedExecutionPlan = SiddhiCompiler.parse(executionPlan); ExecutionPlanConfiguration executionPlanConfiguration = new ExecutionPlanConfiguration(); executionPlanConfiguration.setExecutionPlan(executionPlan); String executionPlanName = AnnotationHelper .getAnnotationElement(EventProcessorConstants.ANNOTATION_NAME_NAME, null, parsedExecutionPlan.getAnnotations()) .getValue(); //Element is not null since the plan is a valid one. executionPlanConfiguration.setName(executionPlanName); Element executionPlanDescriptionElement = AnnotationHelper.getAnnotationElement( EventProcessorConstants.ANNOTATION_NAME_DESCRIPTION, null, parsedExecutionPlan.getAnnotations()); if (executionPlanDescriptionElement != null) { String executionPlanDescription = executionPlanDescriptionElement.getValue(); executionPlanConfiguration.setDescription(executionPlanDescription); } else { executionPlanConfiguration.setDescription(""); } Element isTracingEnabledElement = AnnotationHelper.getAnnotationElement( EventProcessorConstants.ANNOTATION_NAME_TRACE, null, parsedExecutionPlan.getAnnotations()); if (isTracingEnabledElement != null) { String isTracingEnabled = isTracingEnabledElement.getValue(); executionPlanConfiguration.setTracingEnabled(Boolean.valueOf(isTracingEnabled)); } else { executionPlanConfiguration.setTracingEnabled(false); } Element isStatsEnabledElement = AnnotationHelper.getAnnotationElement( EventProcessorConstants.ANNOTATION_NAME_STATISTICS, null, parsedExecutionPlan.getAnnotations()); if (isStatsEnabledElement != null) { String isStatsEnabled = isStatsEnabledElement.getValue(); executionPlanConfiguration.setStatisticsEnabled(Boolean.valueOf(isStatsEnabled)); } else { executionPlanConfiguration.setStatisticsEnabled(false); } executionPlanConfiguration.setEditable(isEditable); ConcurrentHashMap<String, ExecutionPlan> tenantExecutionPlans = tenantSpecificExecutionPlans.get(tenantId); if (tenantExecutionPlans == null) { tenantExecutionPlans = new ConcurrentHashMap<String, ExecutionPlan>(); tenantSpecificExecutionPlans.put(tenantId, tenantExecutionPlans); } else if (tenantExecutionPlans.get(executionPlanName) != null) { // if an execution plan with the same name already exists, we are not going to override it with this plan. throw new ExecutionPlanConfigurationException( "Execution plan with the same name already exists. Please remove it and retry."); } //building Import/Export Map Map<String, String> importsMap = new HashMap<String, String>(); //<SiddhiStreamName, StreamID> Map<String, String> exportsMap = new HashMap<String, String>(); //<SiddhiStreamName, StreamID> for (Map.Entry<String, org.wso2.siddhi.query.api.definition.StreamDefinition> entry : parsedExecutionPlan .getStreamDefinitionMap().entrySet()) { String siddhiStreamName = entry.getKey(); Element importElement = AnnotationHelper.getAnnotationElement(EventProcessorConstants.ANNOTATION_IMPORT, null, entry.getValue().getAnnotations()); Element exportElement = AnnotationHelper.getAnnotationElement(EventProcessorConstants.ANNOTATION_EXPORT, null, entry.getValue().getAnnotations()); if (importElement != null) { String streamId = importElement.getValue(); importsMap.put(siddhiStreamName, streamId); String[] streamIdComponents = streamId.split(EventProcessorConstants.STREAM_SEPARATOR); String streamName = streamIdComponents[0]; String streamVersion = streamIdComponents[1]; executionPlanConfiguration .addImportedStream(new StreamConfiguration(streamName, streamVersion, siddhiStreamName)); } if (exportElement != null) { String streamId = exportElement.getValue(); exportsMap.put(siddhiStreamName, streamId); String[] streamIdComponents = streamId.split(EventProcessorConstants.STREAM_SEPARATOR); String streamName = streamIdComponents[0]; String streamVersion = streamIdComponents[1]; executionPlanConfiguration .addExportedStream(new StreamConfiguration(streamName, streamVersion, siddhiStreamName)); } } Map<String, InputHandler> inputHandlerMap = new ConcurrentHashMap<String, InputHandler>(importsMap.size()); List<String> importDefinitions; List<String> exportDefinitions; importDefinitions = new ArrayList<String>(executionPlanConfiguration.getImportedStreams().size()); for (StreamConfiguration importedStreamConfiguration : executionPlanConfiguration.getImportedStreams()) { StreamDefinition streamDefinition; try { streamDefinition = EventProcessorValueHolder.getEventStreamService() .getStreamDefinition(importedStreamConfiguration.getStreamId()); importDefinitions.add(EventProcessorUtil.getDefinitionString(streamDefinition, importedStreamConfiguration.getSiddhiStreamName())); } catch (EventStreamConfigurationException e) { //ignored as this will not happen } } exportDefinitions = new ArrayList<String>(executionPlanConfiguration.getExportedStreams().size()); for (StreamConfiguration exportedStreamConfiguration : executionPlanConfiguration.getExportedStreams()) { StreamDefinition streamDefinition; try { streamDefinition = EventProcessorValueHolder.getEventStreamService() .getStreamDefinition(exportedStreamConfiguration.getStreamId()); exportDefinitions.add(EventProcessorUtil.getDefinitionString(streamDefinition, exportedStreamConfiguration.getSiddhiStreamName())); } catch (EventStreamConfigurationException e) { //ignored as this will not happen } } /** * Section to handle query deployment */ DistributedConfiguration stormDeploymentConfiguration = EventProcessorValueHolder .getStormDeploymentConfiguration(); try { executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); executionPlanRuntime.handleExceptionWith(new ExceptionHandler<Object>() { @Override public void handleEventException(Throwable throwable, long l, Object o) { log.error(throwable.getMessage(), throwable); if (log.isDebugEnabled()) { log.debug("Event dropped by distruptor due to exception : " + o); } } @Override public void handleOnStartException(Throwable throwable) { log.error("Exception when starting the distruptor process ", throwable); } @Override public void handleOnShutdownException(Throwable throwable) { log.error("Exception when stopping the distruptor process ", throwable); } }); } catch (Exception e) { throw new ExecutionPlanConfigurationException("Invalid query specified, " + e.getMessage(), e); } if (managementInfo.getMode() == Mode.Distributed) { if (stormDeploymentConfiguration != null && stormDeploymentConfiguration.isManagerNode() && EventProcessorValueHolder.getStormManagerServer().isStormCoordinator()) { try { EventProcessorValueHolder.getStormTopologyManager().submitTopology(executionPlanConfiguration, importDefinitions, exportDefinitions, tenantId, stormDeploymentConfiguration.getTopologySubmitRetryInterval()); } catch (StormDeploymentException e) { throw new ExecutionPlanConfigurationException( "Invalid distributed query specified, " + e.getMessage(), e); } } } for (Map.Entry<String, String> entry : importsMap.entrySet()) { inputHandlerMap.put(entry.getValue(), executionPlanRuntime.getInputHandler(entry.getKey())); } //Assumption: executionPlan is valid ExecutionPlan processorExecutionPlan = new ExecutionPlan(executionPlanName, executionPlanRuntime, executionPlanConfiguration); tenantExecutionPlans.put(executionPlanName, processorExecutionPlan); boolean isDistributedEnabledAndIsWorker = (managementInfo.getMode() == Mode.Distributed && stormDeploymentConfiguration != null && stormDeploymentConfiguration.isWorkerNode()); StormStatusMonitor stormStatusMonitor = null; if (isDistributedEnabledAndIsWorker) { StormStatusMapListener mapListener = null; try { stormStatusMonitor = new StormStatusMonitor(tenantId, executionPlanName, importsMap.size()); mapListener = new StormStatusMapListener(executionPlanName, tenantId, stormStatusMonitor); } catch (DeploymentStatusMonitorException e) { log.error("Failed to initialize map listener. Reason: " + e.getMessage(), e); } processorExecutionPlan.setStormStatusMonitor(stormStatusMonitor); processorExecutionPlan.setStormStatusMapListener(mapListener); } /** * Section to configure outputs */ SiddhiStormOutputEventListener stormOutputListener = null; if (managementInfo.getMode() == Mode.Distributed && managementInfo.getDistributedConfiguration().isWorkerNode()) { stormOutputListener = new SiddhiStormOutputEventListener(executionPlanConfiguration, tenantId, stormDeploymentConfiguration, stormStatusMonitor); processorExecutionPlan.addStormOutputListener(stormOutputListener); } for (Map.Entry<String, String> entry : exportsMap.entrySet()) { SiddhiOutputStreamListener streamCallback; try { streamCallback = new SiddhiOutputStreamListener(entry.getKey(), entry.getValue(), executionPlanConfiguration, tenantId); } catch (EventStreamConfigurationException e) { throw new ExecutionPlanConfigurationException(e.getMessage(), e); } try { EventProcessorValueHolder.getEventStreamService().subscribe(streamCallback); } catch (EventStreamConfigurationException e) { //ignored as this will never happen } if (managementInfo.getMode() == Mode.Distributed && stormDeploymentConfiguration != null && stormDeploymentConfiguration.isWorkerNode()) { try { StreamDefinition databridgeDefinition = EventProcessorValueHolder.getEventStreamService() .getStreamDefinition(entry.getValue()); org.wso2.siddhi.query.api.definition.StreamDefinition siddhiStreamDefinition = EventProcessorUtil .convertToSiddhiStreamDefinition(databridgeDefinition, entry.getKey()); stormOutputListener.registerOutputStreamListener(siddhiStreamDefinition, streamCallback); } catch (EventStreamConfigurationException e) { throw new ExecutionPlanConfigurationException(e.getMessage(), e); } } else { executionPlanRuntime.addCallback(entry.getKey(), streamCallback); } processorExecutionPlan.addProducer(streamCallback); } /** * Section to configure inputs */ List<AbstractSiddhiInputEventDispatcher> inputEventDispatchers = new ArrayList<>(); for (Map.Entry<String, String> entry : importsMap.entrySet()) { InputHandler inputHandler = inputHandlerMap.get(entry.getValue()); AbstractSiddhiInputEventDispatcher eventDispatcher; if (isDistributedEnabledAndIsWorker) { StreamDefinition streamDefinition = null; try { streamDefinition = EventProcessorValueHolder.getEventStreamService() .getStreamDefinition(entry.getValue()); } catch (EventStreamConfigurationException e) { // Ignore as this would never happen } eventDispatcher = new SiddhiStormInputEventDispatcher(streamDefinition, entry.getKey(), executionPlanConfiguration, tenantId, stormDeploymentConfiguration, stormStatusMonitor); } else { eventDispatcher = new SiddhiInputEventDispatcher(entry.getValue(), inputHandler, executionPlanConfiguration, tenantId); } inputEventDispatchers.add(eventDispatcher); } if (executionPlanRuntime != null) { executionPlanRuntime.start(); } for (AbstractSiddhiInputEventDispatcher eventDispatcher : inputEventDispatchers) { try { EventProcessorValueHolder.getEventStreamService().subscribe(eventDispatcher); processorExecutionPlan.addConsumer(eventDispatcher); } catch (EventStreamConfigurationException e) { //ignored as this will never happen } } if (EventProcessorValueHolder.getPersistenceConfiguration() != null && managementInfo.getMode() == Mode.HA && managementInfo.getHaConfiguration().isActive()) { executionPlanRuntime.restoreLastRevision(); } }
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);/*from www .j av a 2s .c o 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 ConcurrentHashMap<Integer, HashSet<Integer>> loadCustomerWingInstances() { ConcurrentHashMap<Integer, HashSet<Integer>> instTable = new ConcurrentHashMap<Integer, HashSet<Integer>>(); ResultSet rs = null;/* w w w. j a v a 2s . 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:com.pari.nm.utils.db.InventoryDBHelper.java
public static ConcurrentHashMap<Integer, String> getExternalNodeInfo(String serviceName, Long externalId) throws PariException { ConcurrentHashMap<Integer, String> nodeMap = new ConcurrentHashMap<Integer, String>(1); if (externalId == null || externalId.longValue() <= 0) { throw new PariException("_NCCM_SRV_DEVMGMT_EXTERNALID_MISSING", new Object[] {}); }/*from w w w . j a v a 2s. c o m*/ String query = "select * from external_device where EXTERNAL_ID=" + externalId + " AND SERVICE_NAME= '" + serviceName + "'"; Connection c = DBHelper.getConnection(); ResultSet rs = null; try { rs = DBHelper.executeQueryNoCommit(c, query); if (rs.next()) { String ipAddress = rs.getString("IPADDRESS"); Integer nccmId = rs.getInt("NCCM_ID"); nodeMap.put(nccmId, ipAddress); return nodeMap; } } catch (Exception e) { throw new PariException("_NCCM_SRV_DEVMGMT_GET_EXTERNAL_NODE_INFO_FAILED", new Object[] {}); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (c != null) { try { DBHelper.releaseConnection(c); } catch (Exception ee) { logger.error("Failed to release connection", ee); } } } return null; }
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 w w . j a v a 2 s.com*/ 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.pari.nm.utils.db.InventoryDBHelper.java
public static void loadCollectionProfiles(ConcurrentHashMap<Integer, CollectionProfile> systemDefinedProfiles, ConcurrentHashMap<Integer, CollectionProfile> userDefinedProfiles) { ResultSet rs = null;// w ww . j av a2 s. c o m try { rs = DBHelper.executeQuery("select * from collection_profile"); while (rs.next()) { CollectionProfile prof = new CollectionProfile(); prof.setProfId(rs.getInt("profile_id")); prof.setProfileName(rs.getString("profile_name")); prof.setProfileDescr(rs.getString("profile_descr")); String datasetStr = rs.getString("datasets"); if (datasetStr != null) { prof.setDatasets(datasetStr); } prof.setJobId(rs.getInt("jobid")); if (prof.getJobId() != -1) { if (JobMgr.getInstance().isJobScheduled(prof.getJobId())) { PariJobDetails jDetails = JobMgr.getInstance().getJobDetail(prof.getJobId()); if (jDetails != null) { prof.setScheduleDetails(jDetails.getSchedDetails()); prof.setNotificationPrefs( (CollectionProfileNotificationPrefs) jDetails.getJobSpecificData()); } } } String allDevices = rs.getString("alldevices"); if (allDevices.equals("y")) { prof.setAllDevicesSelected(true); } else { prof.setAllDevicesSelected(false); } StringBuffer sbuf = new StringBuffer(); try { ResultSet rss = DBHelper.executeQuery("select * from collection_prof_devices where profile_id=" + prof.getProfId() + " order by sequence_id"); while (rss.next()) { sbuf.append(rss.getString("device_ids")); } try { rss.close(); } catch (Exception ee) { logger.warn("Exception while closing the resultset in inserting collection profile", ee); } } catch (Exception ee) { logger.warn("Error while loading device to collection profile", ee); } String nodeStr = sbuf.toString(); if (nodeStr != null && nodeStr.length() > 0) { String[] nodeIds = nodeStr.split(","); Integer[] nodes = new Integer[nodeIds.length]; for (int i = 0; i < nodeIds.length; i++) { try { nodes[i] = Integer.parseInt(nodeIds[i]); } catch (Exception ee) { } } prof.setNodes(nodes); } String groupStr = rs.getString("group_ids"); if (groupStr != null && groupStr.trim().length() > 0) { String[] groupIds = groupStr.split(","); Integer[] groups = new Integer[groupIds.length]; for (int i = 0; i < groupIds.length; i++) { try { groups[i] = Integer.parseInt(groupIds[i]); } catch (Exception ee) { } } prof.setGroups(groups); } Timestamp ts = rs.getTimestamp("created_at"); if (ts != null) { prof.setCreatedAt(ts.getTime()); } ts = rs.getTimestamp("modified_at"); if (ts != null) { prof.setModifiedAt(ts.getTime()); } prof.setCreatorId(rs.getInt("creator_id")); prof.setModifierId(rs.getInt("modifier_id")); String sysProfile = rs.getString("system_defined").trim(); if (sysProfile.equals("y")) { prof.setSystemProfile(true); } else { prof.setSystemProfile(false); } int runDiscovery = rs.getInt("run_discovery"); if (runDiscovery == 1) { prof.setRunDiscovery(true); } else { prof.setRunDiscovery(false); } int runDAV = rs.getInt("run_dav"); if (runDAV == 1) { prof.setRunDAV(true); } else { prof.setRunDAV(false); } String cliCommand = rs.getString("cli_command"); prof.setCommandCLI(cliCommand); if (prof.isSystemProfile()) { systemDefinedProfiles.put(prof.getProfId(), prof); } else { userDefinedProfiles.put(prof.getProfId(), prof); } FtpServerDetails ftpDetails = ServerDBHelper.getFtpServerPreferences(prof.getProfileName()); if (ftpDetails != null) { prof.setFtpDetails(ftpDetails); } } } catch (Exception ee) { logger.warn("Error while loading the collection profiles", ee); } finally { try { rs.close(); } catch (Exception ex) { logger.warn("Exception while closing the resultset in inserting collection profile", ex); } } }
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 ww .j av a 2s .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 . co 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) { //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(); } }