private SampleResult waitResponse(SampleResult res, String recipient) throws InterruptedException, SmackException { long time = 0; do { Iterator<Message> packets = responseMessages.iterator(); Thread.sleep(conn.getPacketReplyTimeout() / 100); // optimistic while (packets.hasNext()) { Packet packet = packets.next(); Message response = (Message) packet; if (XmppStringUtils.parseBareAddress(response.getFrom()).equals(recipient)) { packets.remove(); res.setResponseData(response.toXML().toString().getBytes()); if (response.getError() != null) { res.setSuccessful(false); res.setResponseCode("500"); res.setResponseMessage(response.getError().toString()); } return res; } } time += conn.getPacketReplyTimeout() / 10; Thread.sleep(conn.getPacketReplyTimeout() / 10); } while (time < conn.getPacketReplyTimeout()); throw new SmackException.NoResponseException(); }
@Override public void processPacket(Packet packet) throws SmackException.NotConnectedException { if (packet instanceof Message) { Message inMsg = (Message) packet; if (inMsg.getBody() != null) { if (inMsg.getBody().endsWith(NEED_RESPONSE_MARKER)) { if (inMsg.getExtension(NS_DELAYED) == null) { log.debug("Will respond to message: " + inMsg.toXML()); sendResponseMessage(inMsg); } else { log.debug("Will not consider history message: " + inMsg.toXML()); } } else if (inMsg.getBody().endsWith(RESPONSE_MARKER)) { responseMessages.add(inMsg); } } } }
public void process(Packet packet) { if (roomResponseFilter.accept(packet)) { final DiscoverItems result = (DiscoverItems) packet; final JabberPlayer player = playerMgr.getPlayer(packet.getFrom()); // Collect the entityID for each returned item for (Iterator<DiscoverItems.Item> items = result.getItems(); items.hasNext();) { final String roomJID = items.next().getEntityID(); final JabberRoom room = roomMgr.getRoomByJID(JabberClient.this, roomJID); try { room.setInfo(MultiUserChat.getRoomInfo(JabberClient.this .getConnection(), roomJID)); } catch (XMPPException e) { // Ignore Error } if (!roomJID.equals(monitorRoom.getRoom())) { player.join(roomMgr.getRoomByJID(JabberClient.this, roomJID)); } } fireRoomsUpdated(); } else if (newPlayerFilter.accept(packet)) { sendRoomQuery(getAbsolutePlayerJID(packet.getFrom())); } }
/** * This method handles incoming packets. * * @param packet * The incoming packet. * @throws NotConnectedException */ @Override public void processPacket(Packet packet) throws NotConnectedException { if (!(packet instanceof Message)) { return; } Message message = (Message) packet; if (message.getBody() == null) { return; } PacketExtension extension = packet.getExtension(AliasPacketExtension.ALIAS_ELEMENT_NAME, AliasPacketExtension.ALIAS_NAMESPACE); if (extension == null) { sendMessage( packet.getFrom(), packet.getTo(), ResourceBundleManager.instance().getText( "xmpp.message.error.bot", XMPPPatternUtils.extractKenmeiUser(packet.getFrom()) .getLanguageLocale(), XMPPPatternUtils.extractClientIdFromUser(packet.getFrom()), XMPPPatternUtils.getBlogSuffix())); } else { sendMessageToCommunote(message, (AliasPacketExtension) extension); } }
@Override public void processPacket(Packet packet) { if(packet.getFrom().equals(packet.getTo())){ return; } if (packet instanceof Presence) { Presence presence = (Presence) packet; String from = presence.getFrom();//发送方 String to = presence.getTo();//接收方 if (presence.getType().equals(Presence.Type.subscribe)) {//好友申请 Log.e("jj", "好友申请"); } else if (presence.getType().equals(Presence.Type.subscribed)) {//同意添加好友 Log.e("jj", "同意添加好友"); } else if (presence.getType().equals(Presence.Type.unsubscribe)) {//拒绝添加好友 和 删除好友 Log.e("jj", "拒绝添加好友"); } else if (presence.getType().equals(Presence.Type.unsubscribed)){ } else if (presence.getType().equals(Presence.Type.unavailable)) {//好友下线 要更新好友列表,可以在这收到包后,发广播到指定页面 更新列表 Log.e("jj", "好友下线"); } else if(presence.getType().equals(Presence.Type.available)){//好友上线 Log.e("jj", "好友上线"); } else{ Log.e("jj", "error"); } } }
/** * Target should respond with not-acceptable error if no listeners for incoming In-Band * Bytestream requests are registered. * * @throws XMPPException should not happen */ public void testRespondWithErrorOnInBandBytestreamRequest() throws XMPPException { XMPPConnection targetConnection = getConnection(0); XMPPConnection initiatorConnection = getConnection(1); Open open = new Open("sessionID", 1024); open.setFrom(initiatorConnection.getUser()); open.setTo(targetConnection.getUser()); PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter( open.getStanzaId())); initiatorConnection.sendStanza(open); Packet result = collector.nextResult(); assertNotNull(result.getError()); assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition()); }
/** * Target should respond with not-acceptable error if no listeners for incoming Socks5 * bytestream requests are registered. * * @throws XMPPException should not happen */ public void testRespondWithErrorOnSocks5BytestreamRequest() throws XMPPException { XMPPConnection targetConnection = getConnection(0); XMPPConnection initiatorConnection = getConnection(1); Bytestream bytestreamInitiation = Socks5PacketUtils.createBytestreamInitiation( initiatorConnection.getUser(), targetConnection.getUser(), "session_id"); bytestreamInitiation.addStreamHost("proxy.localhost", "127.0.0.1", 7777); PacketCollector collector = initiatorConnection.createPacketCollector(new PacketIDFilter( bytestreamInitiation.getStanzaId())); initiatorConnection.sendStanza(bytestreamInitiation); Packet result = collector.nextResult(); assertNotNull(result.getError()); assertEquals(XMPPError.Condition.no_acceptable.toString(), result.getError().getCondition()); }
/** * Populates the given XMPP packet from the inbound exchange */ public void populateXmppPacket(Packet packet, Exchange exchange) { Set<Map.Entry<String, Object>> entries = exchange.getIn().getHeaders().entrySet(); for (Map.Entry<String, Object> entry : entries) { String name = entry.getKey(); Object value = entry.getValue(); if (!headerFilterStrategy.applyFilterToCamelHeaders(name, value, exchange)) { try { JivePropertiesManager.addProperty(packet, name, value); LOG.debug("Added property name: " + name + " value: " + value.toString()); } catch (IllegalArgumentException iae) { LOG.debug("Not adding property " + name + " to XMPP message due to " + iae); } } } String id = exchange.getExchangeId(); if (id != null) { JivePropertiesManager.addProperty(packet, "exchangeId", id); } }
public Map<String, Object> extractHeadersFromXmpp(Packet xmppPacket, Exchange exchange) { Map<String, Object> answer = new HashMap<String, Object>(); PacketExtension jpe = xmppPacket.getExtension(JivePropertiesExtension.NAMESPACE); if (jpe != null && jpe instanceof JivePropertiesExtension) { extractHeadersFrom((JivePropertiesExtension)jpe, exchange, answer); } if (jpe != null && jpe instanceof DefaultPacketExtension) { extractHeadersFrom((DefaultPacketExtension)jpe, exchange, answer); } if (xmppPacket instanceof Message) { Message xmppMessage = (Message) xmppPacket; answer.put(XmppConstants.MESSAGE_TYPE, xmppMessage.getType()); answer.put(XmppConstants.SUBJECT, xmppMessage.getSubject()); answer.put(XmppConstants.THREAD_ID, xmppMessage.getThread()); } else if (xmppPacket instanceof PubSub) { PubSub pubsubPacket = (PubSub) xmppPacket; answer.put(XmppConstants.MESSAGE_TYPE, pubsubPacket.getType()); } answer.put(XmppConstants.FROM, xmppPacket.getFrom()); answer.put(XmppConstants.PACKET_ID, xmppPacket.getPacketID()); answer.put(XmppConstants.TO, xmppPacket.getTo()); return answer; }
public void processPacket(Packet packet) { if (packet instanceof IQ) { IQ result = (IQ) packet; if (result.getType().equals(IQ.Type.RESULT) && result.getExtensions().isEmpty()) { Collection<String> addedEntries = new ArrayList<String>(); Collection<String> updatedEntries = new ArrayList<String>(); Collection<String> deletedEntries = new ArrayList<String>(); if (persistentStorage != null) { for (RosterPacket.Item item : persistentStorage.getEntries()) { insertRosterItem(item, addedEntries, updatedEntries, deletedEntries); } } fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries); } } connection.removePacketListener(this); }
/** * Sets a filter for all the incoming XMPP-Messages on the Receiver's JID (XMPP-Account ID). * Also creates a listener for the incoming messages and connects the listener to the * XMPPConnection alongside the set filter. * * @param receiverJID the JID (XMPP-Account ID of the receiver) to which the filter is to be * set. */ protected void setFilterOnReceiver(String receiverJID) { filter = new AndFilter(new PacketTypeFilter(Message.class), new ToContainsFilter( receiverJID)); listener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet instanceof Message) { final Message xmppMessage = (Message) packet; Thread msgProcessThread = new Thread() { public void run() { processIncomingMessage(xmppMessage); } }; msgProcessThread.setDaemon(true); msgProcessThread.start(); } } }; connection.addPacketListener(listener, filter); }
/** * Sets a filter for all the incoming XMPP-Messages on the Sender's JID (XMPP-Account ID). * Also creates a listener for the incoming messages and connects the listener to the * XMPPConnection alongside the set filter. * * @param senderJID the JID (XMPP-Account ID of the sender) to which the filter is to be set. */ protected void setFilterOnSender(String senderJID) { filter = new AndFilter(new PacketTypeFilter(Message.class), new FromContainsFilter( senderJID)); listener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet instanceof Message) { final Message xmppMessage = (Message) packet; Thread msgProcessThread = new Thread() { public void run() { processIncomingMessage(xmppMessage); } }; msgProcessThread.setDaemon(true); msgProcessThread.start(); } } }; connection.addPacketListener(listener, filter); }
static public Packet getReply(Connection connection, Packet packet, long timeout) throws XMPPException { PacketFilter responseFilter = new PacketIDFilter(packet.getPacketID()); PacketCollector response = connection.createPacketCollector(responseFilter); connection.sendPacket(packet); // Wait up to a certain number of seconds for a reply. Packet result = response.nextResult(timeout); // Stop queuing results response.cancel(); if (result == null) { throw new XMPPException("No response from server."); } else if (result.getError() != null) { throw new XMPPException(result.getError()); } return result; }
/** * Save this vCard for the user connected by 'connection'. Connection should be authenticated * and not anonymous.<p> * <p/> * NOTE: the method is asynchronous and does not wait for the returned value. * * @param connection the Connection to use. * @throws XMPPException thrown if there was an issue setting the VCard in the server. */ public void save(Connection connection) throws XMPPException { checkAuthenticated(connection, true); setType(IQ.Type.SET); setFrom(connection.getUser()); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(getPacketID())); connection.sendPacket(this); Packet response = collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Cancel the collector. collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } }
/** * Returns the next available packet from the queue for writing. * * @return the next packet for writing. */ private Packet nextPacket() { Packet packet = null; // Wait until there's a packet or we're done. while (!done && (packet = queue.poll()) == null) { try { synchronized (queue) { queue.wait(); } } catch (InterruptedException ie) { // Do nothing } } return packet; }
/** * The server is challenging the SASL mechanism for the stanza he just sent. Send a * response to the server's challenge. * * @param challenge a base64 encoded string representing the challenge. * @throws IOException if an exception sending the response occurs. */ public void challengeReceived(String challenge) throws IOException { byte response[]; if(challenge != null) { response = sc.evaluateChallenge(Base64.decode(challenge)); } else { response = sc.evaluateChallenge(new byte[0]); } Packet responseStanza; if (response == null) { responseStanza = new Response(); } else { responseStanza = new Response(Base64.encodeBytes(response,Base64.DONT_BREAK_LINES)); } // Send the authentication to the server getSASLAuthentication().send(responseStanza); }
public IQ parseIQ(XmlPullParser parser) throws Exception { String sessionID = parser.getAttributeValue("", "sessionID"); List<Packet> packets = new ArrayList<Packet>(); boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("message")) { packets.add(PacketParserUtils.parseMessage(parser)); } else if (parser.getName().equals("presence")) { packets.add(PacketParserUtils.parsePresence(parser)); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("transcript")) { done = true; } } } return new Transcript(sessionID, packets); }
/** * Sends the specified packet to the server. * * @param packet the packet to send. */ public void sendPacket(Packet packet) { if (!done) { // Invoke interceptors for the new packet that is about to be sent. Interceptors // may modify the content of the packet. connection.firePacketInterceptors(packet); try { queue.put(packet); } catch (InterruptedException ie) { ie.printStackTrace(); return; } synchronized (queue) { queue.notifyAll(); } // Process packet writer listeners. Note that we're using the sending // thread so it's expected that listeners are fast. connection.firePacketSendingListeners(packet); } }
@Override public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception { long counter = 0; for (Packet packet : incomingPackets) { incomingPackets.remove(packet); SampleResult subRes = new SampleResult(); subRes.setSuccessful(true); subRes.setResponseCode("200"); subRes.setResponseMessage("OK"); subRes.setSampleLabel(packet.getClass().getSimpleName().isEmpty() ? packet.getClass().getName() : packet.getClass().getSimpleName()); subRes.setResponseData(packet.toXML().toString().getBytes()); if ((packet instanceof Presence) && (((Presence) packet).getType() == Presence.Type.error)) { subRes.setSuccessful(false); subRes.setResponseCode("500"); subRes.setResponseMessage(packet.getError().toString()); } else if ((packet instanceof Message) && (((Message) packet).getType() == Message.Type.error)) { subRes.setSuccessful(false); subRes.setResponseCode("500"); subRes.setResponseMessage(packet.getError().toString()); } else if ((packet instanceof IQ) && (((IQ) packet).getType() == IQ.Type.error)) { subRes.setSuccessful(false); subRes.setResponseCode("500"); subRes.setResponseMessage(packet.getError().toString()); } res.addSubResult(subRes); counter++; } res.setResponseData(("Received packets: " + counter).getBytes()); return counter > 0 ? res : null; }
@Override public SampleResult perform(final JMeterXMPPSampler sampler, SampleResult res) throws Exception { final String xml = sampler.getPropertyAsString(XML); res.setSamplerData(xml); sampler.getXMPPConnection().sendPacket(new Packet() { @Override public CharSequence toXML() { return xml; } }); return res; }
@Override public void processPacket(Packet packet) throws SmackException.NotConnectedException { /** TODO: do we need to respond? if (packet instanceof Presence) { Presence presence = (Presence) packet; if (presence.getType() == Presence.Type.subscribe) { try { conn.getRoster().createEntry(presence.getFrom(), presence.getFrom(), new String[0]); } catch (SmackException.NotLoggedInException | SmackException.NoResponseException | XMPPException.XMPPErrorException e) { log.error("Failed to add to roster", e); } } } */ }
@Override public void processPacket(Packet packet) throws SmackException.NotConnectedException { try { log.debug("Packet recv [" + conn.getConnectionID() + "]: " + packet.toXML()); } catch (IllegalArgumentException e) { log.debug("Failed to log packet", e); log.debug("Packet recv [" + conn.getConnectionID() + "]: " + packet.getError()); } }
public void processPacket(Packet packet) { Message m = (Message) packet; if (ROOM_CHANGE_ACTION.equals(m.getBody())) { String jid = getAbsolutePlayerJID(packet.getFrom()); playerMgr.getPlayer(getAbsolutePlayerJID(packet.getFrom())); sendRoomQuery(jid); } }
public boolean acceptPacket(Packet packet) { boolean accept = false; if (roomResponseFilter.accept(packet)) { accept = QUERY_ROOMS.equals(((DiscoverItems) packet).getNode()); } else if (newPlayerFilter.accept(packet)) { accept = ((Presence) packet).isAvailable(); } return accept; }
protected boolean acceptPacket(Packet packet) { if (chatFilter.accept(packet)) { return true; } if (serverMessageFilter.accept(packet)) { return ((Message) packet).getFrom().equals(JabberClient.this.getConnection().getHost()); } return false; }
protected void process(Packet packet) { if (chatFilter.accept(packet)) { JabberClient.this.processPacket(packet); } else { final Message m = ((Message) packet); JabberClient.this.processServerMessage(m.getSubject(), m.getBody()); } }
public void interceptPacket(Packet packet) { try { intercept(packet); } // FIXME: review error message catch (RuntimeException e) { e.printStackTrace(); } }
public boolean accept(Packet packet) { try { return acceptPacket(packet); } // FIXME: review error message catch (RuntimeException e) { e.printStackTrace(); return false; } }
public void processPacket(Packet packet) { try { process(packet); } // FIXME: review error message catch (RuntimeException e) { e.printStackTrace(); } }
@Override public void processPacket(Packet packet) { Log.d(LOGTAG, "NotificationPacketListener.processPacket()..."); Log.d(LOGTAG, "packet.toXML()=" + packet.toXML()); if (packet instanceof NotificationIQ) { NotificationIQ notification = (NotificationIQ) packet; if (notification.getChildElementXML().contains( "androidpn:iq:notification")) { String notificationId = notification.getId(); String notificationApiKey = notification.getApiKey(); String notificationTitle = notification.getTitle(); String notificationMessage = notification.getMessage(); // String notificationTicker = notification.getTicker(); String notificationUri = notification.getUri(); Intent intent = new Intent(Constants.ACTION_SHOW_NOTIFICATION); intent.putExtra(Constants.NOTIFICATION_ID, notificationId); intent.putExtra(Constants.NOTIFICATION_API_KEY, notificationApiKey); intent .putExtra(Constants.NOTIFICATION_TITLE, notificationTitle); intent.putExtra(Constants.NOTIFICATION_MESSAGE, notificationMessage); intent.putExtra(Constants.NOTIFICATION_URI, notificationUri); // intent.setData(Uri.parse((new StringBuilder( // "notif://notification.androidpn.org/")).append( // notificationApiKey).append("/").append( // System.currentTimeMillis()).toString())); xmppManager.getContext().sendBroadcast(intent); } } }
/** * Handles incoming messages */ @SuppressWarnings("unchecked") @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; FcmPacketExtension fcmPacket = (FcmPacketExtension) incomingMessage.getExtension(Util.FCM_NAMESPACE); String json = fcmPacket.getJson(); try { Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json); Object messageType = jsonMap.get("message_type"); if (messageType == null) { CcsInMessage inMessage = MessageHelper.createCcsInMessage(jsonMap); handleUpstreamMessage(inMessage); // normal upstream message return; } switch (messageType.toString()) { case "ack": handleAckReceipt(jsonMap); break; case "nack": handleNackReceipt(jsonMap); break; case "receipt": handleDeliveryReceipt(jsonMap); break; case "control": handleControlMessage(jsonMap); break; default: logger.log(Level.INFO, "Received unknown FCM message type: " + messageType.toString()); } } catch (ParseException e) { logger.log(Level.INFO, "Error parsing JSON: " + json, e.getMessage()); } }
/** * This method sends a message without an alias, the listener should send an error message back * to the sender. * * @param listener * The listener. * @param connection * The connection. * @throws NotConnectedException */ private void processMessageWithoutAlias(PacketListener listener, XMPPConnection connection) throws NotConnectedException { Message message = new Message(); String sender = user.getAlias() + ".global" + USER_SUFFIX; message.setFrom(sender); message.setThread(blog.getNameIdentifier() + ".global" + BLOG_SUFFIX); message.setBody("Empty"); listener.processPacket(message); Packet packet = connection.getLastPacket(); Assert.assertEquals(packet.getTo(), sender); Assert.assertTrue(((Message) packet).getBody().contains("To post to a topic")); }
/** * This only handles {@link Presence} packets with type "subscribe". {@inheritDoc} * * @throws NotConnectedException */ @Override public void processPacket(Packet packet) throws NotConnectedException { if (!(packet instanceof Presence)) { return; } Presence presence = (Presence) packet; switch (presence.getType()) { case subscribe: sendSubscriptionRequest(presence); break; } }
/** * Test if entity caps actually prevent a disco info request and reply * * @throws XMPPException * */ public void testPreventDiscoInfo() throws XMPPException { con0.addPacketSendingListener(new PacketListener() { @Override public void processPacket(Packet packet) { discoInfoSend = true; } }, new AndFilter(new StanzaTypeFilter(DiscoverInfo.class), new IQTypeFilter(IQ.Type.get))); // add a bogus feature so that con1 ver won't match con0's sdm1.addFeature(DISCOVER_TEST_FEATURE); dropCapsCache(); // discover that DiscoverInfo info = sdm0.discoverInfo(con1.getUser()); // that discovery should cause a disco#info assertTrue(discoInfoSend); assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE)); discoInfoSend = false; // discover that info = sdm0.discoverInfo(con1.getUser()); // that discovery shouldn't cause a disco#info assertFalse(discoInfoSend); assertTrue(info.containsFeature(DISCOVER_TEST_FEATURE)); }