Java 类org.jivesoftware.smack.packet.Stanza 实例源码

项目:BizareChat    文件:BizareChatMessageService.java   
void processReceived(String fromJid, String toJid, String receiptId, Stanza receipt) {
    JobExecutor.getInstance().execute(() -> {
        MessageModel messageModel = daoSession.getMessageModelDao()
                .queryBuilder()
                .where(MessageModelDao.Properties.MessageId.eq(receiptId))
                .unique();

        QueryBuilder<MessageModel> builder = daoSession.getMessageModelDao()
                .queryBuilder();

        List<MessageModel> messages = builder.where(
                builder.and(MessageModelDao.Properties.DateSent.le(messageModel.getDateSent()),
                        MessageModelDao.Properties.ChatDialogId.eq(messageModel.getChatDialogId()),
                        MessageModelDao.Properties.SenderId.eq(CurrentUser.getInstance().getCurrentUserId().intValue()),
                        MessageModelDao.Properties.Read.eq(MessageState.DEFAULT)))
                .list();

        for (MessageModel message : messages) {
            message.setRead(MessageState.DELIVERED);
        }

        EventBus.getDefault().post(new ReceivedEvent(messages));

        daoSession.getMessageModelDao().updateInTx(messages);
    });
}
项目:BizareChat    文件:BizareChatMessageService.java   
void processDisplayed(String fromJid, String toJid, String receiptId, Stanza receipt) {
    JobExecutor.getInstance().execute(() -> {
        MessageModel messageModel = daoSession.getMessageModelDao()
                .queryBuilder()
                .where(MessageModelDao.Properties.MessageId.eq(receiptId))
                .unique();

        QueryBuilder<MessageModel> builder = daoSession.getMessageModelDao()
                .queryBuilder();

        List<MessageModel> messages = builder.where(
                builder.and(MessageModelDao.Properties.DateSent.le(messageModel.getDateSent()),
                        MessageModelDao.Properties.ChatDialogId.eq(messageModel.getChatDialogId()),
                        MessageModelDao.Properties.SenderId.eq(CurrentUser.getInstance().getCurrentUserId().intValue()),
                        MessageModelDao.Properties.Read.notEq(MessageState.READ)))
                .list();

        for (MessageModel message : messages) {
            message.setRead(MessageState.READ);
        }

        EventBus.getDefault().post(new DisplayedEvent(messages));

        daoSession.getMessageModelDao().updateInTx(messages);
    });
}
项目:Smack    文件:TranscriptProvider.java   
@Override
public Transcript parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException {
    String sessionID = parser.getAttributeValue("", "sessionID");
    List<Stanza> packets = new ArrayList<Stanza>();

    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);
}
项目:Smack    文件:InBandBytestreamSession.java   
public boolean accept(Stanza packet) {
    // sender equals remote peer
    if (!packet.getFrom().equalsIgnoreCase(remoteJID)) {
        return false;
    }

    DataPacketExtension data;
    if (packet instanceof Data) {
        data = ((Data) packet).getDataPacketExtension();
    } else {
        // stanza contains data packet extension
        data = packet.getExtension(
                DataPacketExtension.ELEMENT,
                DataPacketExtension.NAMESPACE);
        if (data == null) {
            return false;
        }
    }

    // session ID equals this session ID
    if (!data.getSessionID().equals(byteStreamRequest.getSessionID())) {
        return false;
    }

    return true;
}
项目:lider    文件:AgreementStatusListener.java   
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
    try {
        if (packet instanceof Message) {

            Message msg = (Message) packet;
            logger.info("Agreement status message received from => {}, body => {}", msg.getFrom(), msg.getBody());

            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm"));

            // Construct message
            AgreementStatusMessageImpl message = mapper.readValue(msg.getBody(), AgreementStatusMessageImpl.class);
            message.setFrom(msg.getFrom());

            if (subscriber != null) {
                subscriber.messageReceived(message);
                logger.debug("Notified subscriber => {}", subscriber);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
项目:lider    文件:ScriptResultListener.java   
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
    try {
        if (packet instanceof Message) {

            Message msg = (Message) packet;
            logger.info("Script result message received from => {}, body => {}", msg.getFrom(), msg.getBody());

            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm"));

            // Construct message
            ScriptResultMessageImpl message = mapper.readValue(msg.getBody(), ScriptResultMessageImpl.class);
            message.setFrom(msg.getFrom());

            if (subscriber != null) {
                subscriber.messageReceived(message);
                logger.debug("Notified subscriber => {}", subscriber);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
项目:Smack    文件:FromMatchesFilterTest.java   
@Test
public void bareCompareMatchingServiceJid()
{
    FromMatchesFilter filter = FromMatchesFilter.createBare(SERVICE_JID1);
    Stanza packet = new Stanza() {
        @Override
        public String toXML() { return null; }
    };

    packet.setFrom(SERVICE_JID1);
    assertTrue(filter.accept(packet));

    packet.setFrom(SERVICE_JID2);
    assertFalse(filter.accept(packet));

    packet.setFrom(BASE_JID1);
    assertFalse(filter.accept(packet));

    packet.setFrom(FULL_JID1_R1);
    assertFalse(filter.accept(packet));

    packet.setFrom(BASE_JID3);
    assertFalse(filter.accept(packet));
}
项目:Smack    文件:AbstractXMPPConnection.java   
@Override
public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) {
    final StanzaListener packetListener = new StanzaListener() {
        @Override
        public void processPacket(Stanza packet) throws NotConnectedException {
            try {
                callback.processPacket(packet);
            } finally {
                removeSyncStanzaListener(this);
            }
        }
    };
    addSyncStanzaListener(packetListener, packetFilter);
    removeCallbacksService.schedule(new Runnable() {
        @Override
        public void run() {
            removeSyncStanzaListener(packetListener);
        }
    }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
项目:Smack    文件:SynchronizationPoint.java   
/**
 * Send the given top level stream element and wait for a response.
 *
 * @param request the plain stream element to send.
 * @throws NoResponseException if no response was received.
 * @throws NotConnectedException if the connection is not connected.
 */
public void sendAndWaitForResponse(TopLevelStreamElement request) throws NoResponseException,
                NotConnectedException {
    assert (state == State.Initial);
    connectionLock.lock();
    try {
        if (request != null) {
            if (request instanceof Stanza) {
                connection.sendStanza((Stanza) request);
            }
            else if (request instanceof PlainStreamElement){
                connection.send((PlainStreamElement) request);
            } else {
                throw new IllegalStateException("Unsupported element type");
            }
            state = State.RequestSent;
        }
        waitForConditionOrTimeout();
    }
    finally {
        connectionLock.unlock();
    }
    checkForResponse();
}
项目:Smack    文件:FromMatchesFilterTest.java   
@Test
public void autoCompareMatchingServiceJid()
{
    FromMatchesFilter filter = FromMatchesFilter.create(SERVICE_JID1);
    Stanza packet = new Stanza() {
        @Override
        public String toXML() { return null; }
    };

    packet.setFrom(SERVICE_JID1);
    assertTrue(filter.accept(packet));

    packet.setFrom(SERVICE_JID2);
    assertFalse(filter.accept(packet));

    packet.setFrom(BASE_JID1);
    assertFalse(filter.accept(packet));

    packet.setFrom(FULL_JID1_R1);
    assertFalse(filter.accept(packet));

    packet.setFrom(BASE_JID3);
    assertFalse(filter.accept(packet));
}
项目:Smack    文件:IQReplyFilter.java   
@Override
public boolean accept(Stanza packet) {
    // First filter out everything that is not an IQ stanza and does not have the correct ID set.
    if (!iqAndIdFilter.accept(packet))
        return false;

    // Second, check if the from attributes are correct and log potential IQ spoofing attempts
    if (fromFilter.accept(packet)) {
        return true;
    } else {
        String msg = String.format("Rejected potentially spoofed reply to IQ-packet. Filter settings: "
                        + "packetId=%s, to=%s, local=%s, server=%s. Received packet with from=%s",
                        packetId, to, local, server, packet.getFrom());
        LOGGER.log(Level.WARNING, msg , packet);
        return false;
    }
}
项目:Smack    文件:InBandBytestreamSession.java   
protected StanzaListener getDataPacketListener() {
    return new StanzaListener() {

        public void processPacket(Stanza packet) {
            // get data packet extension
            DataPacketExtension data = (DataPacketExtension) packet.getExtension(
                            DataPacketExtension.ELEMENT,
                            DataPacketExtension.NAMESPACE);

            // check if encoded data is valid
            if (data.getDecodedData() == null) {
                /*
                 * TODO once a majority of XMPP server implementation support XEP-0079
                 * Advanced Message Processing the invalid message could be answered with an
                 * appropriate error. For now we just ignore the packet. Subsequent packets
                 * with an increased sequence will cause the input stream to close the
                 * stream/session.
                 */
                return;
            }

            // data is valid; add to data queue
            dataQueue.offer(data);

            // TODO confirm packet once XMPP servers support XEP-0079
        }

    };
}
项目:mangosta-android    文件:XMPPSession.java   
public void sendStanza(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
    if (Preferences.isTesting()) {
        try {
            getXMPPConnection().sendStanza(stanza);
        } catch (SmackException.NotConnectedException | InterruptedException e) {
            e.printStackTrace();
        }
    } else {
        getXMPPConnection().sendStanza(stanza);
    }
}
项目:Smack    文件:Socks5TransferNegotiator.java   
@Override
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPErrorException,
                InterruptedException, SmackException {
    /*
     * SOCKS5 initiation listener must ignore next SOCKS5 Bytestream request with given session
     * ID
     */
    this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());

    Stanza streamInitiation = initiateIncomingStream(this.connection, initiation);
    return negotiateIncomingStream(streamInitiation);
}
项目:Smack    文件:ChatConnectionTest.java   
private void processServerMessage(Stanza incomingChat) {
    TestChatServer chatServer = new TestChatServer(incomingChat, dc);
    chatServer.start();
    try {
        chatServer.join();
    } catch (InterruptedException e) {
        fail();
    }
    waitListener.waitAndReset();
}
项目:Smack    文件:DelayInformationManager.java   
/**
 * Get Delayed Delivery information. This method first looks for a PacketExtension with the
 * XEP-203 namespace and falls back to the XEP-91 namespace.
 *
 * @param packet
 * @return the Delayed Delivery information or <code>null</code>
 */
public static DelayInformation getDelayInformation(Stanza packet) {
    DelayInformation delayInformation = getXep203DelayInformation(packet);
    if (delayInformation != null) {
        return delayInformation;
    }
    return getLegacyDelayInformation(packet);
}
项目:lider    文件:RegistrationListener.java   
@Override
public boolean accept(Stanza stanza) {
    if (stanza instanceof Message) {
        Message msg = (Message) stanza;
        // All messages from agents are type normal
        // Message body must contain one of these strings => "type":
        // "REGISTER" or "type": "UNREGISTER"
        if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) {
            return true;
        }
    }
    return false;
}
项目:lider    文件:MissingPluginListener.java   
@Override
public boolean accept(Stanza stanza) {
    if (stanza instanceof Message) {
        Message msg = (Message) stanza;
        // All messages from agents are type normal
        // Message body must contain => "type": "MISSING_PLUGIN"
        if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) {
            return true;
        }
    }
    return false;
}
项目:Smack    文件:Node.java   
public void processPacket(Stanza packet)
{
       EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns());
    ConfigurationEvent config = (ConfigurationEvent)event.getEvent();

    listener.handleNodeConfiguration(config);
}
项目:lider    文件:PacketListener.java   
@Override
public void processPacket(Stanza packet) throws NotConnectedException {
    try {
        logger.debug("Packet received: {}", packet.toXML());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
项目:lider    文件:AgreementStatusListener.java   
@Override
public boolean accept(Stanza stanza) {
    if (stanza instanceof Message) {
        Message msg = (Message) stanza;
        // All messages from agents are type normal
        // Message body must contain => "type": "REQUEST_AGREEMENT"
        if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) {
            return true;
        }
    }
    return false;
}
项目:Smack    文件:FromMatchesFilterTest.java   
@Test
    public void bareCompareMatchingBaseJid()
    {
        FromMatchesFilter filter = FromMatchesFilter.createBare(BASE_JID1);
        Stanza packet = new Stanza() {
            @Override
            public String toXML() { return null; }
        };

        packet.setFrom(BASE_JID1);
        assertTrue(filter.accept(packet));

        packet.setFrom(FULL_JID1_R1);
        assertTrue(filter.accept(packet));

        packet.setFrom(FULL_JID1_R2);
        assertTrue(filter.accept(packet));

        packet.setFrom(BASE_JID2);
        assertFalse(filter.accept(packet));

        packet.setFrom(FULL_JID2);
        assertFalse(filter.accept(packet));

        packet.setFrom(BASE_JID3);
        assertFalse(filter.accept(packet));
}
项目:lider    文件:PolicyStatusListener.java   
@Override
public boolean accept(Stanza stanza) {
    if (stanza instanceof Message) {
        Message msg = (Message) stanza;
        // All messages from agents are type normal
        if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) {
            return true;
        }
    }
    return false;
}
项目:lider    文件:ScriptResultListener.java   
@Override
public boolean accept(Stanza stanza) {
    if (stanza instanceof Message) {
        Message msg = (Message) stanza;
        // All messages from agents are type normal
        // Message body must contain => "type": "SCRIPT_RESULT"
        if (Message.Type.normal.equals(msg.getType()) && messagePattern.matcher(msg.getBody()).matches()) {
            return true;
        }
    }
    return false;
}
项目:Smack    文件:AgentRoster.java   
public void processPacket(Stanza packet) {
    if (packet instanceof AgentStatusRequest) {
        AgentStatusRequest statusRequest = (AgentStatusRequest)packet;
        for (Iterator<AgentStatusRequest.Item> i = statusRequest.getAgents().iterator(); i.hasNext();) {
            AgentStatusRequest.Item item = i.next();
            String agentJID = item.getJID();
            if ("remove".equals(item.getType())) {

                // Removing the user from the roster, so remove any presence information
                // about them.
                String key = XmppStringUtils.parseLocalpart(XmppStringUtils.parseLocalpart(agentJID) + "@" +
                        XmppStringUtils.parseDomain(agentJID));
                presenceMap.remove(key);
                // Fire event for roster listeners.
                fireEvent(EVENT_AGENT_REMOVED, agentJID);
            }
            else {
                entries.add(agentJID);
                // Fire event for roster listeners.
                fireEvent(EVENT_AGENT_ADDED, agentJID);
            }
        }

        // Mark the roster as initialized.
        rosterInitialized = true;
    }
}
项目:Smack    文件:XMPPTCPConnection.java   
private void drainWriterQueueToUnacknowledgedStanzas() {
    List<Element> elements = new ArrayList<Element>(queue.size());
    queue.drainTo(elements);
    for (Element element : elements) {
        if (element instanceof Stanza) {
            unacknowledgedStanzas.add((Stanza) element);
        }
    }
}
项目:Smack    文件:ShortcutPredicates.java   
@Override
public boolean accept(Stanza packet) {
    for (StanzaFilter predicate : predicates) {
        if (predicate.accept(packet)) {
            return true;
        }
    }
    return false;
}
项目:Smack    文件:ForEveryMessage.java   
@Override
public boolean accept(Stanza packet) {
    if (packet instanceof Message) {
        return true;
    }
    return false;
}
项目:Smack    文件:ReportedData.java   
/**
 * Returns a new ReportedData if the stanza(/packet) is used for reporting data and includes an 
 * extension that matches the elementName and namespace "x","jabber:x:data".
 * 
 * @param packet the stanza(/packet) used for reporting data.
 */
public static ReportedData getReportedDataFrom(Stanza packet) {
    // Check if the packet includes the DataForm extension
    DataForm dataForm = DataForm.from(packet);
    if (dataForm != null) {
        if (dataForm.getReportedData() != null)
            return new ReportedData(dataForm);
    }
    // Otherwise return null
    return null;
}
项目:Smack    文件:CarbonManager.java   
/**
 * Notify server to change the carbons state. This method returns
 * immediately and changes the variable when the reply arrives.
 *
 * You should first check for support using isSupportedByServer().
 *
 * @param new_state whether carbons should be enabled or disabled
 * @throws NotConnectedException 
 */
public void sendCarbonsEnabled(final boolean new_state) throws NotConnectedException {
    IQ setIQ = carbonsEnabledIQ(new_state);

    connection().sendIqWithResponseCallback(setIQ, new StanzaListener() {
        public void processPacket(Stanza packet) {
            enabled_state = new_state;
        }
    });
}
项目:Smack    文件:MultipleRecipientManager.java   
/**
 * Sends the specified stanza(/packet) to the collection of specified recipients using the specified
 * connection. If the server has support for XEP-33 then only one stanza(/packet) is going to be sent to
 * the server with the multiple recipient instructions. However, if XEP-33 is not supported by
 * the server then the client is going to send the stanza(/packet) to each recipient.
 * 
 * @param connection the connection to use to send the packet.
 * @param packet the stanza(/packet) to send to the list of recipients.
 * @param to the collection of JIDs to include in the TO list or <tt>null</tt> if no TO list exists.
 * @param cc the collection of JIDs to include in the CC list or <tt>null</tt> if no CC list exists.
 * @param bcc the collection of JIDs to include in the BCC list or <tt>null</tt> if no BCC list
 *        exists.
 * @param replyTo address to which all replies are requested to be sent or <tt>null</tt>
 *        indicating that they can reply to any address.
 * @param replyRoom JID of a MUC room to which responses should be sent or <tt>null</tt>
 *        indicating that they can reply to any address.
 * @param noReply true means that receivers should not reply to the message.
 * @throws XMPPErrorException if server does not support XEP-33: Extended Stanza Addressing and
 *         some XEP-33 specific features were requested.
 * @throws NoResponseException if there was no response from the server.
 * @throws FeatureNotSupportedException if special XEP-33 features where requested, but the
 *         server does not support them.
 * @throws NotConnectedException 
 */
public static void send(XMPPConnection connection, Stanza packet, Collection<String> to, Collection<String> cc, Collection<String> bcc,
        String replyTo, String replyRoom, boolean noReply) throws NoResponseException, XMPPErrorException, FeatureNotSupportedException, NotConnectedException {
    // Check if *only* 'to' is set and contains just *one* entry, in this case extended stanzas addressing is not
    // required at all and we can send it just as normal stanza without needing to add the extension element
    if (to != null && to.size() == 1 && (cc == null || cc.isEmpty()) && (bcc == null || bcc.isEmpty()) && !noReply
                    && StringUtils.isNullOrEmpty(replyTo) && StringUtils.isNullOrEmpty(replyRoom)) {
        String toJid = to.iterator().next();
        packet.setTo(toJid);
        connection.sendStanza(packet);
        return;
    }
    String serviceAddress = getMultipleRecipienServiceAddress(connection);
    if (serviceAddress != null) {
        // Send packet to target users using multiple recipient service provided by the server
        sendThroughService(connection, packet, to, cc, bcc, replyTo, replyRoom, noReply,
                serviceAddress);
    }
    else {
        // Server does not support XEP-33 so try to send the packet to each recipient
        if (noReply || (replyTo != null && replyTo.trim().length() > 0) ||
                (replyRoom != null && replyRoom.trim().length() > 0)) {
            // Some specified XEP-33 features were requested so throw an exception alerting
            // the user that this features are not available
            throw new FeatureNotSupportedException("Extended Stanza Addressing");
        }
        // Send the packet to each individual recipient
        sendToIndividualRecipients(connection, packet, to, cc, bcc);
    }
}
项目:Smack    文件:PacketCollector.java   
/**
 * Returns the next available packet. The method call will block (not return) until a stanza(/packet) is
 * available.
 * 
 * @return the next available packet.
 */
@SuppressWarnings("unchecked")
public <P extends Stanza> P nextResultBlockForever() {
    throwIfCancelled();
    P res = null;
    while (res == null) {
        try {
            res = (P) resultQueue.take();
        } catch (InterruptedException e) {
            LOGGER.log(Level.FINE,
                            "nextResultBlockForever was interrupted", e);
        }
    }
    return res;
}
项目:Smack    文件:FromMatchesFilterTest.java   
@Test
    public void autoCompareMatchingBaseJid()
    {
        FromMatchesFilter filter = FromMatchesFilter.create(BASE_JID1);
        Stanza packet = new Stanza() {
            @Override
            public String toXML() { return null; }
        };

        packet.setFrom(BASE_JID1);
        assertTrue(filter.accept(packet));

        packet.setFrom(FULL_JID1_R1);
        assertTrue(filter.accept(packet));

        packet.setFrom(FULL_JID1_R2);
        assertTrue(filter.accept(packet));

        packet.setFrom(BASE_JID2);
        assertFalse(filter.accept(packet));

        packet.setFrom(FULL_JID2);
        assertFalse(filter.accept(packet));

        packet.setFrom(BASE_JID3);
        assertFalse(filter.accept(packet));
}
项目:Smack    文件:PacketCollector.java   
/**
 * Processes a stanza(/packet) to see if it meets the criteria for this stanza(/packet) collector.
 * If so, the stanza(/packet) is added to the result queue.
 *
 * @param packet the stanza(/packet) to process.
 */
protected void processPacket(Stanza packet) {
    if (packetFilter == null || packetFilter.accept(packet)) {
        while (!resultQueue.offer(packet)) {
            // Since we know the queue is full, this poll should never actually block.
            resultQueue.poll();
        }
        if (collectorToReset != null) {
            collectorToReset.waitStart = System.currentTimeMillis();
        }
    }
}