private void sendRemoteChannelServerNotFoundErrorResponses(String server) throws ComponentException { List<Packet> queued = waitingStanzas.get(server); if (queued == null) { return; } Element noRemoteServer = new DOMElement("text", new Namespace("", JabberPubsub.NS_PUBSUB_ERROR)); noRemoteServer.setText("No pubsub channel service discovered for " + server); Element itemNotFound = new DOMElement( PacketError.Condition.item_not_found.toXMPP(), new Namespace("", JabberPubsub.NS_XMPP_STANZAS)); Element error = new DOMElement("error"); error.addAttribute("type", PacketError.Type.cancel.toXMPP()); error.add(itemNotFound); error.add(noRemoteServer); IQ response; for (Packet packet : queued) { response = IQ.createResultIQ((IQ) packet); response.setFrom(localServer); response.setType(IQ.Type.error); response.setChildElement(error); component.sendPacket(response); } }
public void receivedAnswer(IQ packet) { String packetId = packet.getID(); if (isValid(packet)) { // The packet was validated, so it can be added to the Entity // Capabilities cache map. // Add the resolved identities and features to the entity // EntityCapabilitiesManager.capabilities object and add it // to the cache map... EntityCapabilities caps = verAttributes.get(packetId); // Store identities. List<String> identities = getIdentitiesFrom(packet); for (String identity : identities) { caps.addIdentity(identity); } // Store features. List<String> features = getFeaturesFrom(packet); for (String feature : features) { caps.addFeature(feature); } entityCapabilitiesMap.put(caps.getVerAttribute(), caps); entityCapabilitiesUserMap.put(packet.getFrom(), caps.getVerAttribute()); } // Remove cached 'ver' attribute. verAttributes.remove(packetId); }
/* * Create the SessionCredit * the information retrieved from the iq */ protected SessionCredit getSessionCredit(final IQ iq) { String maxseconds = null; String type = null; SessionCredit sessionCredit = new SessionCredit(SessionCredit.RouteType.ip); sessionCredit.setMaxDurationInSeconds(0); log.debug("Get Credit Value Received: " + iq.toXML()); final Element e = iq.getChildElement(); maxseconds = e.attributeValue("maxseconds"); type = e.attributeValue("type"); if (maxseconds != null && type != null) { try { final int seconds = Integer.parseInt(maxseconds); sessionCredit.setMaxDurationInSeconds(seconds); final SessionCredit.RouteType rt = SessionCredit.RouteType.valueOf(type); sessionCredit.setRouteType(rt); } catch (IllegalFormatException ife) { log.error("Invalid Credit Value Received: " + iq.toXML(), ife); } catch (IllegalArgumentException ife) { log.error("Invalid Route Type Value Received: " + iq.toXML(), ife); } } else { log.debug("Call Initialized with Default Credits: " + iq.toXML()); } return sessionCredit; }
/** Issue #230 */ @Test public void badRsmValueReturnsValidError() throws Exception { String after = "/user/[email protected]/posts/example.com|94948"; Element rsm = new BaseElement(new QName("set", new Namespace("", "http://jabber.org/protocol/rsm"))); rsm.addElement("after").setText(after); String stanza = "<iq type=\"get\" to=\"channels.buddycloud.org\" " + "from=\"[email protected]/resource\" id=\"id:1\">" + "<pubsub xmlns=\"http://jabber.org/protocol/pubsub\">" + "<user-items xmlns=\"http://buddycloud.org/v1\" parent-only=\"true\" " + "since=\"2000-01-01T00:00:00.000Z\"/>" + "<set xmlns=\"http://jabber.org/protocol/rsm\">" + "<max>10</max>" + "<after>/user/[email protected]/posts/example.com|94948</after>" + "</set>" + "</pubsub>" + "</iq>"; IQ request = this.toIq(stanza); userItemsGet.process(element, jid, request, rsm); Assert.assertEquals(1, queue.size()); IQ response = (IQ) queue.poll(); PacketError errorPacket = response.getError(); Assert.assertEquals("Could not parse the 'after' id: " + after, errorPacket.getText()); Assert.assertEquals(PacketError.Condition.bad_request, errorPacket.getCondition()); Assert.assertEquals(PacketError.Type.modify, errorPacket.getType()); }
/** * Processes an IQ-register request that is expressing the wish to deregister from a gateway. * * @param packet the IQ-register stanza. */ private void handleDeregister(final IQ packet) { final IQ result = IQ.createResultIQ(packet); if (packet.getChildElement().elements().size() != 1) { Log.debug( "Cannot process this stanza - exactly one" + " childelement of <remove> expected:" + packet.toXML()); final IQ error = IQ.createResultIQ(packet); error.setError(Condition.bad_request); parent.sendPacket(error); return; } final JID from = packet.getFrom(); final JID to = packet.getTo(); // Tell the end user the transport went byebye. final Presence unavailable = new Presence(Presence.Type.unavailable); unavailable.setTo(from); unavailable.setFrom(to); this.parent.sendPacket(unavailable); try { deleteRegistration(from); } catch (UserNotFoundException e) { Log.debug("Error cleaning up contact list of: " + from); result.setError(Condition.registration_required); } parent.sendPacket(result); }
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { // We only want packets recieved by the server if (!processed && incoming && packet instanceof IQ) { IQ iq = (IQ) packet; Element childElement = iq.getChildElement(); if (childElement == null) { return; } String namespace = childElement.getNamespaceURI(); String profile = childElement.attributeValue("profile"); // Check that the SI is about file transfer and try creating a file transfer if (NAMESPACE_SI.equals(namespace) && NAMESPACE_SI_FILETRANSFER.equals(profile)) { // If this is a set, check the feature offer if (iq.getType().equals(IQ.Type.set)) { JID from = iq.getFrom(); JID to = iq.getTo(); FileTransfer transfer = createFileTransfer(from, to, childElement); try { if (transfer == null || !acceptIncomingFileTransferRequest(transfer)) { throw new PacketRejectedException(); } } catch (FileTransferRejectedException e) { throw new PacketRejectedException(e); } } } } }
public void executeGet(IQ packet, Workgroup workgroup) { IQ reply = IQ.createResultIQ(packet); JID from = packet.getFrom(); String bareJID = from.toBareJID(); boolean isMonitor = false; // Retrieve the sound settings. String monitors = workgroup.getProperties().getProperty("monitors"); if (monitors != null) { StringTokenizer tkn = new StringTokenizer(monitors, ","); while (tkn.hasMoreTokens()) { String agent = tkn.nextToken(); if (agent.equalsIgnoreCase(bareJID)) { isMonitor = true; } } } Element monitorElement = reply.setChildElement("monitor", "http://jivesoftware.com/protocol/workgroup"); if (!isMonitor) { monitorElement.addElement("isMonitor").setText("false"); } else { monitorElement.addElement("isMonitor").setText("true"); } workgroup.send(reply); }
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { if (!processed && packet instanceof IQ && !incoming) { // Check for the Bookmark Storage element and hand off to the Bookmark engine. IQ iq = (IQ) packet; Element childElement = iq.getChildElement(); if (childElement == null || iq.getType() != IQ.Type.result) { return; } String namespace = childElement.getNamespaceURI(); if ("jabber:iq:private".equals(namespace)) { // In private data, when a user is attempting to retrieve bookmark // information, there will be a storage:bookmarks namespace. Element storageElement = childElement.element("storage"); if (storageElement == null) { return; } namespace = storageElement.getNamespaceURI(); if ("storage:bookmarks".equals(namespace)) { // Append Server defined bookmarks for user. JID toJID = iq.getTo(); addBookmarks(toJID, storageElement); } } } }
public void process(Presence packet) { // Ignore unavailable presences if (Presence.Type.unavailable == packet.getType()) { return; } // Examine the packet and check if it has caps info, // if not -- do nothing by returning. Element capsElement = packet.getChildElement("c", "http://jabber.org/protocol/caps"); if (capsElement == null) { return; } // Examine the packet and check if it's in legacy format (pre version 1.4 // of XEP-0115). If so, do nothing by returning. // TODO: if this packet is in legacy format, we SHOULD check the 'node', // 'ver', and 'ext' combinations as specified in the archived version // 1.3 of the specification, and cache the results. See JM-1447 final String hashAttribute = capsElement.attributeValue("hash"); if (hashAttribute == null || hashAttribute.trim().length() == 0) { return; } // Examine the packet and check if it has and a 'ver' hash // if not -- do nothing by returning. final String newVerAttribute = capsElement.attributeValue("ver"); if (newVerAttribute == null || newVerAttribute.trim().length() == 0) { return; } // Check to see if the 'ver' hash is already in our cache. if (isInCapsCache(newVerAttribute)) { // The 'ver' hash is in the cache already, so let's update the // entityCapabilitiesUserMap for the user that sent the caps // packet. entityCapabilitiesUserMap.put(packet.getFrom(), newVerAttribute); } else { // The 'ver' hash is not in the cache so send out a disco#info query // so that we may begin recognizing this 'ver' hash. IQ iq = new IQ(IQ.Type.get); iq.setTo(packet.getFrom()); String serverName = XmppServer.getInstance().getServerInfo().getXMPPDomain(); iq.setFrom(serverName); iq.setChildElement("query", "http://jabber.org/protocol/disco#info"); String packetId = iq.getID(); final EntityCapabilities caps = new EntityCapabilities(); caps.setHashAttribute(hashAttribute); caps.setVerAttribute(newVerAttribute); verAttributes.put(packetId, caps); final IQRouter iqRouter = XmppServer.getInstance().getIQRouter(); iqRouter.addIQResultListener(packetId, this); iqRouter.route(iq); } }
public String getRelatedNodeForRemotePacket(IQ packet) { String id = null; if (nodeMap.containsKey(packet.getID())) { id = (String) nodeMap.get(packet.getID()); nodeMap.remove(packet.getID()); } return id; }
private void fail(IQ request, Condition condition, org.xmpp.packet.PacketError.Type type) throws InterruptedException { IQ reply = IQ.createResultIQ(request); reply.setType(Type.error); PacketError pe = new PacketError(condition, type); reply.setError(pe); outQueue.put(reply); }
/* * (non-Javadoc) * * @see * com.buddycloud.pusher.handler.AbstractQueryHandler#handleQuery(org.xmpp * .packet.IQ) */ @Override protected IQ handleQuery(IQ iq) { String userJid = iq.getFrom().toBareJID(); Element queryElement = iq.getElement().element("query"); Element typeEl = queryElement.element("type"); NotificationSettings notificationSettings = NotificationUtils.getNotificationSettingsByType(userJid, typeEl.getText(), getDataSource()); return createResponse(iq, userJid, notificationSettings); }
protected IQ error(Packet packet, PacketError.Condition condition) { IQ reply; reply = new IQ(IQ.Type.error, packet.getID()); reply.setFrom(packet.getTo()); reply.setTo(packet.getFrom()); reply.setError(condition); return reply; }
private void unregister(IQ request, JID actorJID, boolean isRemote) throws Exception { LOGGER.debug("Processing unregister request from " + request.getFrom()); if (!validateSingleChildElement(request)) { failBadRequest(request); return; } if (!isRemote && !userRegistered(actorJID)) { failRegistrationRequired(request); return; } Transaction t = null; try { t = channelManager.beginTransaction(); List<Packet> notifications = new LinkedList<Packet>(); Set<String> remoteDomains = getRemoteDomains(); ResultSet<NodeMembership> userMemberships = channelManager.getUserMemberships(actorJID); for (NodeMembership userMembership : userMemberships) { String nodeId = userMembership.getNodeId(); if (isPersonal(nodeId) || isSingleOwner(nodeId, actorJID)) { channelManager.deleteNode(nodeId); if (Configuration.getInstance().isLocalNode(nodeId)) { addDeleteNodeNotifications(nodeId, notifications); } } if (!isRemote) { addUnsubscribeFromNodeNotifications(actorJID, userMembership.getNodeId(), notifications); } } ResultSet<NodeItem> userItems = channelManager.getUserPublishedItems(actorJID); for (NodeItem userItem : userItems) { if (Configuration.getInstance().isLocalNode(userItem.getNodeId())) { addDeleteItemNotifications(userItem.getNodeId(), userItem.getId(), notifications); } } channelManager.deleteUserItems(actorJID); channelManager.deleteUserSubscriptions(actorJID); channelManager.deleteUserAffiliations(actorJID); outQueue.put(IQ.createResultIQ(request)); if (!isRemote) { makeRemoteRequests(request, remoteDomains); } sendNotifications(notifications); t.commit(); } finally { if (t != null) { t.close(); } } }
@SuppressWarnings("unchecked") @Test @Ignore public void testCanControlGatheredEntriesUsingRsm() throws Exception { NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "node1:1", new Date(0), "<entry>item1</entry>"); NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "node2:1", new Date(10), "<entry>item2</entry>"); NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "node1:2", new Date(20), "<entry>item3</entry>"); NodeItem item4 = new NodeItemImpl(TEST_NODE_1, "node1:3", new Date(30), "<entry>item4</entry>"); ArrayList<NodeItem> results = new ArrayList<NodeItem>(); results.add(item1); results.add(item2); results.add(item3); results.add(item4); Mockito.when( channelManager.getUserFeedItems( Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyInt(), Mockito.any(GlobalItemID.class), Mockito.anyBoolean())) .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator())); Mockito.when( channelManager.getCountUserFeedItems( Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyBoolean())) .thenReturn(results.size()); Element rsm = request.getElement().addElement("rsm"); rsm.addNamespace("", PubSubElementProcessorAbstract.NS_RSM); rsm.addElement("max").addText("2"); rsm.addElement("after").addText("node1:1"); userItemsGet.process(element, jid, request, null); IQ response = (IQ) queue.poll(); Assert.assertEquals(IQ.Type.result, response.getType()); Element pubsub = response.getChildElement(); Assert.assertEquals("pubsub", pubsub.getName()); Assert.assertEquals(JabberPubsub.NAMESPACE_URI, pubsub.getNamespaceURI()); List<Element> items = pubsub.elements("items"); Assert.assertEquals(2, items.size()); Assert.assertEquals(TEST_NODE_2, items.get(0).attributeValue("node")); Assert.assertEquals(TEST_NODE_1, items.get(1).attributeValue("node")); Assert.assertEquals(1, items.get(0).elements("item").size()); Assert.assertEquals(1, items.get(1).elements("item").size()); Element rsmResult = pubsub.element("set"); Assert.assertEquals("2", rsmResult.element("count").getText()); Assert.assertEquals("node2:1", rsmResult.element("first").getText()); Assert.assertEquals("node1:2", rsmResult.element("last").getText()); }
private void discoverRemoteChannelServer(String remoteDomain, String id) throws ComponentException { logger.info("Attemping to discover remote server " + remoteDomain); IQ discover = new IQ(IQ.Type.get); discover.setFrom(localServer); discover.setTo(remoteDomain); discover.setID(id); discover.getElement().addElement("query", JabberPubsub.NS_DISCO_ITEMS); component.sendPacket(discover); remoteChannelDiscoveryStatus.put(remoteDomain, DISCO_ITEMS); }
/** * Send a disco#info request to the new component. If the component provides information then it * will be added to the list of discoverable server items. * * @param component the new component that was added to this manager. * @param componentJID the XMPP address of the new component. */ private void checkDiscoSupport(Component component, JID componentJID) { // Build a disco#info request that will be sent to the component IQ iq = new IQ(IQ.Type.get); iq.setFrom(getAddress()); iq.setTo(componentJID); iq.setChildElement("query", "http://jabber.org/protocol/disco#info"); // Send the disco#info request to the component. The reply (if any) will be processed in // #process(Packet) // sendPacket(component, iq); component.processPacket(iq); }
/** * 审批入群申请 * * @param iq * @return */ private IQ processGroupApply(IQ iq) { IQ reply = IQ.createResultIQ(iq); // 发送者 String creator = iq.getFrom().toBareJID(); Element query = iq.getChildElement(); // 申请人 String applier = query.elementText("applier"); // 审批结果 String result = query.elementText("result"); if (result == null || applier == null || (!GroupApply.STATUS_ACCEPT.equals(result) && !GroupApply.STATUS_DENIED.equals(result))) { reply.setError(PacketError.Condition.bad_request); return reply; } long group_id = -1; LocalGroup localGroup = null; try { group_id = Long.parseLong(iq.getTo().getNode()); localGroup = service.getGroup(group_id); } catch (Exception e) { reply.setError(PacketError.Condition.bad_request); return reply; } try { // 检查是否已经处理过这条请求 GroupApply apply = groupDbManager.getGroupApplyByUserGroupId(group_id, applier); if (apply == null && !localGroup.isOwner(creator)) { reply.setError(PacketError.Condition.bad_request); return reply; } // 处理请求 apply.setStatus(result); groupDbManager.processGroupApply(apply); // 如果申请人在线,发送消息通知 Message applier_msg = packetUtil.createGroupApplyResponseMessage(apply, localGroup.getGroup()); boolean sent = sendPacketIfOnline(applier_msg, apply.getApply_user()); // 未发送,保存到数据库 if (!sent) { GroupSysMessage sysMessage = new GroupSysMessage(apply.getApply_user(), applier_msg.toXML()); groupDbManager.insertGroupSysMessage(sysMessage); } // 如果是同意,发送presence给群成员 if (GroupApply.STATUS_ACCEPT.equals(apply.getStatus())) { // 发送消息 sendPacket( localGroup.getGroupMembers().keySet(), packetUtil.createNewMemberPresence(apply)); } // 处理完成 } catch (SQLException e) { reply.setError(PacketError.Condition.internal_server_error); } return reply; }
public IQ handleIQ(IQ iq) { Type type = iq.getType(); String group_id = iq.getTo().getNode(); if (group_id == null) return null; // 申请入群 if (Type.get == type) return applyUserGroup(iq); else if (Type.set == type) { Element element = iq.getChildElement(); Element quit = element.element("quit"); if (quit != null) return quitGroup(iq); else return processGroupApply(iq); } return null; }
public void featureNotImplementedSuccess() throws IOException, InterruptedException, DocumentException { IQ request = readStanzaAsIq("/iq/featureNotImplemented/request.stanza"); String expectedReply = readStanzaAsString("/iq/featureNotImplemented/reply.stanza"); TestHelper helper = new TestHelper(); helper.getInQueue().put(request); IQ replyIQ = (IQ) helper.getOutQueue().poll(1000, TimeUnit.MILLISECONDS); Assert.assertNotNull(replyIQ); Assert.assertEquals(expectedReply, replyIQ.toXML()); }
private void processIQ(IQ iq) { long start = System.currentTimeMillis(); Element childElement = iq.getChildElement(); String namespace = childElement.getNamespaceURI(); // 构造返回dom IQ reply = IQ.createResultIQ(iq); Element childElementCopy = childElement.createCopy(); reply.setChildElement(childElementCopy); if (XConstants.PROTOCOL_DISCO_INFO.equals(namespace)) { generateDisco(childElementCopy); // 构造disco反馈信息 if (LOG.isInfoEnabled()) { LOG.info( "[spend time:{}ms],reqId: {},IRComponent服务发现,response:{}", System.currentTimeMillis() - start, iq.getID(), reply.toXML()); } } try { ComponentManagerFactory.getComponentManager().sendPacket(this, reply); } catch (Throwable t) { LOG.error( "[spend time:{}ms],reqId: {},IRComponent IQ处理异常! iq:{},replay:{}", System.currentTimeMillis() - start, iq.getID(), reply.toXML(), t); } }
public ServerRequestIQ( JID fromAddress, JID toAddress, String method, String action, Map<String, String> headerMap, String bodyText) { super(IQ.Type.set); if (fromAddress != null) super.setFrom(fromAddress); if (toAddress != null) super.setTo(toAddress); addOpenHomeElement(method, action, headerMap, bodyText); }
private void processIQ(Element doc) { log.debug("processIQ()..."); IQ packet; try { packet = getIQ(doc); } catch (IllegalArgumentException e) { log.debug("Rejecting packet. JID malformed", e); IQ reply = new IQ(); if (!doc.elements().isEmpty()) { reply.setChildElement(((Element) doc.elements().get(0)).createCopy()); } reply.setID(doc.attributeValue("id")); reply.setTo(session.getAddress()); String to = doc.attributeValue("to"); if (to != null) { reply.getElement().addAttribute("from", to); } reply.setError(PacketError.Condition.jid_malformed); session.process(reply); return; } // if (packet.getID() == null) { // // IQ packets MUST have an 'id' attribute // StreamError error = new StreamError( // StreamError.Condition.invalid_xml); // session.deliverRawText(error.toXML()); // session.close(); // return; // } packet.setFrom(session.getAddress()); router.route(packet); session.incrementClientPacketCount(); }
/** * The packet is a typical 'set' or 'get' update targeted at the server. Notice that the set could * be a roster removal in which case we have to generate a local roster removal update as well as * a new roster removal to send to the the roster item's owner. * * @param packet The packet that triggered this update * @return Either a response to the roster update or null if the packet is corrupt and the session * was closed down */ private IQ manageRoster(org.xmpp.packet.Roster packet) throws UnauthorizedException, UserAlreadyExistsException, SharedGroupException { IQ returnPacket = null; JID sender = packet.getFrom(); IQ.Type type = packet.getType(); try { if ((sender.getNode() == null || !RosterManager.isRosterServiceEnabled() || !userManager.isRegisteredUser(sender.getNode())) && IQ.Type.get == type) { // If anonymous user asks for his roster or roster service is disabled then // return an empty roster IQ reply = IQ.createResultIQ(packet); reply.setChildElement("query", "jabber:iq:roster"); return reply; } if (!localServer.isLocal(sender)) { // Sender belongs to a remote server so discard this IQ request Log.warn("Discarding IQ roster packet of remote user: " + packet); return null; } Roster cachedRoster = userManager.getUser(sender.getNode()).getRoster(); if (IQ.Type.get == type) { returnPacket = cachedRoster.getReset(); returnPacket.setType(IQ.Type.result); returnPacket.setTo(sender); returnPacket.setID(packet.getID()); // Force delivery of the response because we need to trigger // a presence probe from all contacts deliverer.deliver(returnPacket); returnPacket = null; } else if (IQ.Type.set == type) { for (org.xmpp.packet.Roster.Item item : packet.getItems()) { if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) { removeItem(cachedRoster, packet.getFrom(), item); } else { if (cachedRoster.isRosterItem(item.getJID())) { // existing item RosterItem cachedItem = cachedRoster.getRosterItem(item.getJID()); cachedItem.setAsCopyOf(item); cachedRoster.updateRosterItem(cachedItem); } else { // new item cachedRoster.createRosterItem(item); } } } returnPacket = IQ.createResultIQ(packet); } } catch (UserNotFoundException e) { throw new UnauthorizedException(e); } return returnPacket; }
/** * Processes packets that were sent to this service. Currently only packets that were sent from * registered components are being processed. In the future, we may also process packet of trusted * clients. Trusted clients may be able to execute ad-hoc commands such as adding or removing * components. * * @param packet the packet to process. */ @Override public void process(Packet packet) throws PacketException { List<Component> components = getComponents(packet.getFrom()); // Only process packets that were sent by registered components if (!components.isEmpty()) { if (packet instanceof IQ && IQ.Type.result == ((IQ) packet).getType()) { IQ iq = (IQ) packet; Element childElement = iq.getChildElement(); if (childElement != null) { String namespace = childElement.getNamespaceURI(); if ("http://jabber.org/protocol/disco#info".equals(namespace)) { // Add a disco item to the server for the component that supports disco Element identity = childElement.element("identity"); if (identity == null) { // Do nothing since there are no identities in the disco#info packet return; } try { XMPPServer.getInstance() .getIQDiscoItemsHandler() .addComponentItem(packet.getFrom().toBareJID(), identity.attributeValue("name")); for (Component component : components) { if (component instanceof ComponentSession.ExternalComponent) { ComponentSession.ExternalComponent externalComponent = (ComponentSession.ExternalComponent) component; externalComponent.setName(identity.attributeValue("name")); externalComponent.setType(identity.attributeValue("type")); externalComponent.setCategory(identity.attributeValue("category")); } } } catch (Exception e) { Log.error( "Error processing disco packet of components: " + components + " - " + packet.toXML(), e); } // Store the IQ disco#info returned by the component addComponentInfo(iq); // Notify listeners that a component answered the disco#info request notifyComponentInfo(iq); // Alert other cluster nodes CacheFactory.doClusterTask(new NotifyComponentInfo(iq)); } } } } }
@Override public void processPacket(Packet packet) { if (packet instanceof Message) { Message message = (Message) packet; processMessage(message); } else if (packet instanceof Presence) { Presence presence = (Presence) packet; processPresence(presence); } else if (packet instanceof IQ) { IQ iq = (IQ) packet; if (IQ.Type.error == iq.getType() || IQ.Type.result == iq.getType()) { return; } processIQ(iq); } }
public void componentInfoReceived(IQ iq) { // Check if it's a Clearspace component boolean isClearspace = false; Element childElement = iq.getChildElement(); for (Iterator it = childElement.elementIterator("identity"); it.hasNext(); ) { Element identity = (Element) it.next(); if ("component".equals(identity.attributeValue("category")) && "clearspace".equals(identity.attributeValue("type"))) { isClearspace = true; } } // If component is Clearspace then keep track of the component if (isClearspace) { clearspaces.add(iq.getFrom().getDomain()); } }
/** * Configures the subscription based on the sent {@link DataForm} included in the IQ packet sent * by the subscriber. If the subscription was pending of configuration then the last published * item is going to be sent to the subscriber. * * <p>The originalIQ parameter may be <tt>null</tt> when using this API internally. When no IQ * packet was sent then no IQ result will be sent to the sender. The rest of the functionality is * the same. * * @param originalIQ the IQ packet sent by the subscriber to configure his subscription or null * when using this API internally. * @param options the data form containing the new subscription configuration. */ public void configure(IQ originalIQ, DataForm options) { boolean wasUnconfigured = isConfigurationPending(); // Change the subscription configuration based on the completed form configure(options); if (originalIQ != null) { // Return success response service.send(IQ.createResultIQ(originalIQ)); } if (wasUnconfigured) { // If subscription is pending then send notification to node owners // asking to approve the now configured subscription if (isAuthorizationPending()) { sendAuthorizationRequest(); } // Send last published item (if node is leaf node and subscription status is ok) if (node.isSendItemSubscribe() && isActive()) { PublishedItem lastItem = node.getLastPublishedItem(); if (lastItem != null) { sendLastPublishedItem(lastItem); } } } }
public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm) throws Exception { element = elm; response = IQ.createResultIQ(reqIQ); request = reqIQ; actor = actorJID; node = element.attributeValue("node"); if (null == actor) { actor = request.getFrom(); } if (!channelManager.isLocalNode(node)) { makeRemoteRequest(); return; } try { if (!nodeProvided() || !nodeExists() || !actorCanModify()) { outQueue.put(response); return; } } catch (NodeStoreException e) { LOGGER.error(e); setErrorCondition(PacketError.Type.cancel, PacketError.Condition.internal_server_error); outQueue.put(response); return; } setNodeConfiguration(); }
@Override public IQ query(Component component, IQ packet, long timeout) throws ComponentException { final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<>(8); XMPPServer.getInstance() .getIQRouter() .addIQResultListener( packet.getID(), new IQResultListener() { @Override public void receivedAnswer(IQ packet) { answer.offer(packet); } @Override public void answerTimeout(String packetId) { Log.warn( "An answer to a previously sent IQ stanza was never received. Packet id: " + packetId); } }); sendPacket(component, packet); IQ reply = null; try { reply = answer.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Ignore } return reply; }