public void registerListener(Class<? extends MessageListener> listenerClass) { MessageListener listener = null; try { listener = listenerClass.newInstance(); } catch (Exception e) { log.error(String.format("listener \"%s\" newInstance is error. ", listenerClass), e); return; } MessageAction actions = new MessageAction(); listener.onRegisterAction(actions); for (String action : actions.getActions()) { List<MessageListener> list = listenerMap.get(action); if (null == list) { list = new ArrayList<MessageListener>(); } if (!list.contains(listener)) { list.add(listener); } listenerMap.put(action, list); } }
@Override public void handleMessage(Message msg) { MessageListener listener = this.listener.get(); if (listener != null) { listener.handleMessage(msg); } }
private void notifyListener( final FetchRequest request, final MessageIterator it, final MessageListener listener) { if (listener != null) { if (listener.getExecutor() != null) { try { listener .getExecutor() .execute( new Runnable() { @Override public void run() { FetchRequestRunner.this.receiveMessages(request, it, listener); } }); } catch (final RejectedExecutionException e) { log.error( "MessageListener线程池繁忙,无法处理消息,topic=" + request.getTopic() + ",partition=" + request.getPartition(), e); SimpleFetchManager.this.addFetchRequest(request); } } else { this.receiveMessages(request, it, listener); } } }
@Override public void onStart(Intent intent, int startid) { super.onStart(intent, startid); if (mMessageListener.getStatus() != Status.RUNNING) { mMessageListener.execute(intent.getStringExtra("channel")); } }
public synchronized void messageReceived(int to, Message m) { DrainMsg mhMsg = (DrainMsg) m; log.debug( "incoming: localDest: " + to + " type:" + mhMsg.get_type() + " hops:" + (16 - mhMsg.get_ttl()) + " seqNo:" + mhMsg.get_seqNo() + " source:" + mhMsg.get_source() + " finalDest:" + mhMsg.get_dest()); // lets assume that the network cannot buffer more than 25 drain msgs from a single source at a // time (should be more than reasonable) if (seqNos.containsKey(new Integer(mhMsg.get_source()))) { int oldSeqNo = ((Integer) seqNos.get(new Integer(mhMsg.get_source()))).intValue(); int upperBound = mhMsg.get_seqNo() + 25; int wrappedUpperBound = 25 - (255 - mhMsg.get_seqNo()); if ((oldSeqNo >= mhMsg.get_seqNo() && oldSeqNo < upperBound) || (oldSeqNo >= 0 && oldSeqNo < wrappedUpperBound)) { log.debug( "Dropping message from " + mhMsg.get_source() + " with duplicate seqNo: " + mhMsg.get_seqNo()); return; } } seqNos.put(new Integer(mhMsg.get_source()), new Integer(mhMsg.get_seqNo())); if (to != spAddr && to != MoteIF.TOS_BCAST_ADDR && to != TOS_UART_ADDR) { log.debug("Dropping message not for me."); return; } HashSet promiscuousSet = (HashSet) idTable.get(new Integer(BCAST_ID)); HashSet listenerSet = (HashSet) idTable.get(new Integer(mhMsg.get_type())); if (listenerSet != null && promiscuousSet != null) { listenerSet.addAll(promiscuousSet); } else if (listenerSet == null && promiscuousSet != null) { listenerSet = promiscuousSet; } if (listenerSet == null) { log.debug("No Listener for type: " + mhMsg.get_type()); return; } for (Iterator it = listenerSet.iterator(); it.hasNext(); ) { MessageListener ml = (MessageListener) it.next(); ml.messageReceived(to, mhMsg); } }
/** * Delivers a message directly to this chat, which will add the message to the collector and * deliver it to all listeners registered with the Chat. This is used by the XMPPConnection class * to deliver messages without a thread ID. * * @param message the message. */ void deliver(Message message) { // Because the collector and listeners are expecting a thread ID with // a specific value, set the thread ID on the message even though it // probably never had one. message.setThread(threadID); for (MessageListener listener : listeners) { listener.processMessage(this, message); } }
@SuppressWarnings("unchecked") private Message onMessage(Message message) { Map<String, MessageListener> listeners = AppContext.getApplicationContext().getBeansOfType(MessageListener.class); for (MessageListener listener : listeners.values()) { if (listener.support(message)) { return listener.onMessage(message); } } return null; }
public void notify(Message message) { log(message); if (!message.isTransient()) { // put the newest messages up front; old messages are at the end this.messages.addFirst(message); if (messages.size() > maxMessages) { messages .removeLast(); // we should only have 1 extra, so removeLast should remove all extras } } for (MessageListener listener : listeners) { listener.onMessage(message); } }
/** * @param channel name to subscribe to * @param listener callback for messages received * @param timetoken the time since the last read from the server. This value is usually sent with * a result from the subscribe RESt method on the server. */ private void doSubscribe(String channel, MessageListener listener, String timetoken) { while (true) { try { // Build URL List<String> url = java.util.Arrays.asList("subscribe", this.subscribeKey, channel, "0", timetoken); // Wait for Message JsonNode response = doRequest(url); JsonNode messages = response.get(0); // Update TimeToken if (response.get(1).getTextValue().length() > 0) { timetoken = response.get(1).getTextValue(); } // Run user Callback and Reconnect if user permits. If // there's a timeout then messages.length() == 0. for (int i = 0; messages.size() > i; i++) { JsonNode message = messages.get(i); if (!listener.onMessage(message)) { return; } } } catch (Exception e) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } } }
public static void main(String[] args) { MessageListener ml = new MessageListener(); InsertDbMessageExe idme = new InsertDbMessageExe(); ml.add(idme); FileUpdateMessageExe fume = new FileUpdateMessageExe(); ml.add(fume); ml.setMessage("one"); // ml.notice(); System.out.println("============================="); ml.setMessage("two"); // notice.notice(); }
private boolean notifyOnMessage( MessageListener listener, ServerSession from, ServerMessage message) { try { return listener.onMessage(this, from, message); } catch (Throwable x) { _logger.info("Exception while invoking listener " + listener, x); return true; } }
public String handleMessage(WXAccount wxaccount, String reqdata) { Map<String, String> msgData = parseRequestXml(reqdata); String msgType = msgData.get("MsgType"); try { Class<?> clazz = receiveMessageMap.get(msgType); if (clazz == null) { log.error("[{}] 处理消息时对应的类型[{}]没有解析器!", wxaccount.getSystemId(), msgType); return ""; } ReceiveMessage receiveMessage = (ReceiveMessage) clazz.newInstance(); // 对上行的消息进行解析 receiveMessage.parse(msgData); // 将上行的消息调用每一个侦听器对象 String messageType = receiveMessage.getMsgType(); List<MessageListener> messageListenerList = new LinkedList<MessageListener>(this.commonMessageListenerList); if (this.messageListenerMap.containsKey(messageType)) { messageListenerList.addAll(this.messageListenerMap.get(messageType)); } ResponseMessage respMessage = null; for (MessageListener listener : messageListenerList) { respMessage = listener.onMessage(wxaccount, receiveMessage); // 注意,如果有多个侦听器关注一个类型的消息话,以第一个有返回的为主,后续的侦听器将不再起作用 if (respMessage != null) { // 保存下行消息 WXMessage.dao.saveResponseMessage(wxaccount.getId(), respMessage); // 返回下行消息 return respMessage.toXML(); } } } catch (Exception e) { log.error("[{}] 处理消息时未正确初始化[{}]", wxaccount.getSystemId(), msgType); return ""; } // 回复此字符串表示服务器已经处理,微信不需要再重发相同的消息 return "success"; }
/** * Performs an atomic {@link #receiveNoWait()} and dispatch to the listener within the STOP_GUARD * which ensures that the consumer cannot be stopped until the listener has completed processing * of the message. * * @param listener the listener to which to dispatch * @return true if a message was dispatched, false otherwise * @throws JMSException */ protected boolean receiveAndDispatch(BlockingQueue<byte[]> queue, MessageListener listener) throws JMSException { synchronized (STOP_GUARD) { Message msg = receive(queue, 0); if (msg != null) { listener.onMessage(msg); return true; } else { return false; } } }
@Test public void testWriteWhileReading() { ClassAliasPool.CLASS_ALIASES.addAlias(Message1.class); ClassAliasPool.CLASS_ALIASES.addAlias(Message2.class); File path1 = Utils.tempDir("testWriteWhileReading1"); File path2 = Utils.tempDir("testWriteWhileReading2"); try (SingleChronicleQueue queue1 = SingleChronicleQueueBuilder.binary(path1).testBlockSize().build(); SingleChronicleQueue queue2 = SingleChronicleQueueBuilder.binary(path2).testBlockSize().build()) { MethodReader reader2 = queue1.createTailer().methodReader(ObjectUtils.printAll(MessageListener.class)); MessageListener writer2 = queue2.acquireAppender().methodWriter(MessageListener.class); MessageListener processor = new MessageProcessor(writer2); MethodReader reader1 = queue1.createTailer().methodReader(processor); MessageListener writer1 = queue1.acquireAppender().methodWriter(MessageListener.class); for (int i = 0; i < 3; i++) { // write a message writer1.method1(new Message1("hello")); writer1.method2(new Message2(234)); // read those messages assertTrue(reader1.readOne()); assertTrue(reader1.readOne()); assertFalse(reader1.readOne()); // read the produced messages assertTrue(reader2.readOne()); assertTrue(reader2.readOne()); assertFalse(reader2.readOne()); } // System.out.println(queue1.dump()); } }
/** * 返回是否需要跳过后续的处理 * * @param request * @param it * @param listener * @param partition * @return */ private boolean processReceiveMessage( final FetchRequest request, final MessageIterator it, final MessageListener listener, final Partition partition) { int count = 0; while (it.hasNext()) { final int prevOffset = it.getOffset(); try { final Message msg = it.next(); MessageAccessor.setPartition(msg, partition); if (((SimpleMessageConsumer) consumer).canConsumer(msg)) listener.recieveMessages(msg); if (partition.isAutoAck()) { count++; } else { // 提交或者回滚都必须跳出循环 if (partition.isAcked()) { count++; break; } else if (partition.isRollback()) { break; } else { // 不是提交也不是回滚,仅递增计数 count++; } } } catch (final InvalidMessageException e) { MetaStatLog.addStat(null, StatConstants.INVALID_MSG_STAT, request.getTopic()); // 消息体非法,获取有效offset,重新发起查询 this.getOffsetAddRequest(request, e); return true; } catch (final Throwable e) { // 将指针移到上一条消息 it.setOffset(prevOffset); log.error( "MessageListener处理消息异常,topic=" + request.getTopic() + ",partition=" + request.getPartition(), e); // 跳出循环,处理消息异常,到此为止 break; } } MetaStatLog.addStatValue2(null, StatConstants.GET_MSG_COUNT_STAT, request.getTopic(), count); return false; }
/** * Creates the Bloom filter * * @param msg Message * @param inBuffer Input buffer * @param msgListener Message listener * @throws EOFException End-of-data processing input stream * @throws VerificationException Verification error */ public static void processFilterLoadMessage( Message msg, SerializedBuffer inBuffer, MessageListener msgListener) throws EOFException, VerificationException { // // Load the new bloom filter // Peer peer = msg.getPeer(); BloomFilter newFilter = new BloomFilter(inBuffer); BloomFilter oldFilter; synchronized (peer) { oldFilter = peer.getBloomFilter(); newFilter.setPeer(peer); peer.setBloomFilter(newFilter); } // // Notify the message listener // msgListener.processFilterLoad(msg, oldFilter, newFilter); }
/** * Process the 'getblocks' message and return an 'inv' message * * @param msg Message * @param inBuffer Input buffer * @param msgListener Message listener * @throws EOFException End-of-data processing stream * @throws VerificationException Message verification failed */ public static void processGetBlocksMessage( Message msg, SerializedBuffer inBuffer, MessageListener msgListener) throws EOFException, VerificationException { // // Process the message // int version = inBuffer.getInt(); if (version < NetParams.MIN_PROTOCOL_VERSION) throw new VerificationException( String.format("Protocol version %d is not supported", version)); int count = inBuffer.getVarInt(); if (count < 0 || count > 500) throw new VerificationException("More than 500 locator entries in 'getblocks' message"); List<Sha256Hash> blockList = new ArrayList<>(count); for (int i = 0; i < count; i++) blockList.add(new Sha256Hash(Helper.reverseBytes(inBuffer.getBytes(32)))); Sha256Hash stopBlock = new Sha256Hash(Helper.reverseBytes(inBuffer.getBytes(32))); // // Notify the message listener // msgListener.processGetBlocks(msg, version, blockList, stopBlock); }
public int hashCode() { return listener.hashCode(); }
@Override public void method2(Message2 message) { message.number += 1000; writer2.method2(message); }
protected void fireMessageSent(Message message) { for (MessageListener messageListener : messageListeners) messageListener.messageSent(this, message); }
private void fireMessageReceived(Message message) { for (MessageListener messageListener : messageListeners) messageListener.messageReceived(this, message); }
protected Object handleUpEvent(Event evt) throws Exception { switch (evt.getType()) { case Event.MSG: if (msg_listener != null) msg_listener.receive((Message) evt.getArg()); break; case Event.GET_APPLSTATE: // reply with GET_APPLSTATE_OK byte[] tmp_state = null; if (msg_listener != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); msg_listener.getState(output); tmp_state = output.toByteArray(); } return new StateTransferInfo(null, 0L, tmp_state); case Event.GET_STATE_OK: if (msg_listener != null) { StateTransferResult result = (StateTransferResult) evt.getArg(); if (result.hasBuffer()) { ByteArrayInputStream input = new ByteArrayInputStream(result.getBuffer()); msg_listener.setState(input); } } break; case Event.STATE_TRANSFER_OUTPUTSTREAM: OutputStream os = (OutputStream) evt.getArg(); if (msg_listener != null && os != null) { msg_listener.getState(os); } break; case Event.STATE_TRANSFER_INPUTSTREAM: InputStream is = (InputStream) evt.getArg(); if (msg_listener != null && is != null) msg_listener.setState(is); break; case Event.VIEW_CHANGE: View v = (View) evt.getArg(); List<Address> new_mbrs = v.getMembers(); setMembers(new_mbrs); if (membership_listener != null) membership_listener.viewAccepted(v); break; case Event.SET_LOCAL_ADDRESS: if (log.isTraceEnabled()) log.trace("setting local_addr (" + local_addr + ") to " + evt.getArg()); local_addr = (Address) evt.getArg(); break; case Event.SUSPECT: if (membership_listener != null) membership_listener.suspect((Address) evt.getArg()); break; case Event.BLOCK: if (membership_listener != null) membership_listener.block(); break; case Event.UNBLOCK: if (membership_listener != null) membership_listener.unblock(); break; } return null; }
@Override public void method1(Message1 message) { message.text += "-processed"; writer2.method1(message); }