Java 类org.jivesoftware.smack.XMPPException.XMPPErrorException 实例源码

项目:Smack    文件:PubSubManager.java   
/**
 * Creates a node with specified configuration.
 * 
 * Note: This is the only way to create a collection node.
 * 
 * @param name The name of the node, which must be unique within the 
 * pubsub service
 * @param config The configuration for the node
 * @return The node that was created
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public Node createNode(String name, Form config) throws NoResponseException, XMPPErrorException, NotConnectedException
{
    PubSub request = PubSub.createPubsubPacket(to, Type.set, new NodeExtension(PubSubElementType.CREATE, name), null);
    boolean isLeafNode = true;

    if (config != null)
    {
        request.addExtension(new FormNode(FormNodeType.CONFIGURE, config));
        FormField nodeTypeField = config.getField(ConfigureNodeFields.node_type.getFieldName());

        if (nodeTypeField != null)
            isLeafNode = nodeTypeField.getValues().get(0).equals(NodeType.leaf.toString());
    }

    // Errors will cause exceptions in getReply, so it only returns
    // on success.
    sendPubsubPacket(con, request);
    Node newNode = isLeafNode ? new LeafNode(con, name) : new CollectionNode(con, name);
    newNode.setTo(to);
    nodeMap.put(newNode.getId(), newNode);

    return newNode;
}
项目:Smack    文件:InBandBytestreamManagerTest.java   
/**
 * Invoking {@link InBandBytestreamManager#establishSession(String)} should
 * throw an exception if the given target does not support in-band
 * bytestream.
 * @throws SmackException 
 * @throws XMPPException 
 */
@Test
public void shouldFailIfTargetDoesNotSupportIBB() throws SmackException, XMPPException {
    InBandBytestreamManager byteStreamManager = InBandBytestreamManager.getByteStreamManager(connection);

    try {
        XMPPError xmppError = new XMPPError(
                        XMPPError.Condition.feature_not_implemented);
        IQ errorIQ = IBBPacketUtils.createErrorIQ(targetJID, initiatorJID, xmppError);
        protocol.addResponse(errorIQ);

        // start In-Band Bytestream
        byteStreamManager.establishSession(targetJID);

        fail("exception should be thrown");
    }
    catch (XMPPErrorException e) {
        assertEquals(XMPPError.Condition.feature_not_implemented,
                        e.getXMPPError().getCondition());
    }

}
项目:Smack    文件:AgentSession.java   
/**
 * Sets the agent's current status with the workgroup. The presence mode affects how offers
 * are routed to the agent. The possible presence modes with their meanings are as follows:<ul>
 * <p/>
 * <li>Presence.Mode.AVAILABLE -- (Default) the agent is available for more chats
 * (equivalent to Presence.Mode.CHAT).
 * <li>Presence.Mode.DO_NOT_DISTURB -- the agent is busy and should not be disturbed.
 * However, special case, or extreme urgency chats may still be offered to the agent.
 * <li>Presence.Mode.AWAY -- the agent is not available and should not
 * have a chat routed to them (equivalent to Presence.Mode.EXTENDED_AWAY).</ul>
 *
 * @param presenceMode the presence mode of the agent.
 * @param status       sets the status message of the presence update.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 * @throws IllegalStateException if the agent is not online with the workgroup.
 */
public void setStatus(Presence.Mode presenceMode, String status) throws NoResponseException, XMPPErrorException, NotConnectedException {
    if (!online) {
        throw new IllegalStateException("Cannot set status when the agent is not online.");
    }

    if (presenceMode == null) {
        presenceMode = Presence.Mode.available;
    }
    this.presenceMode = presenceMode;

    Presence presence = new Presence(Presence.Type.available);
    presence.setMode(presenceMode);
    presence.setTo(this.getWorkgroupJID());

    if (status != null) {
        presence.setStatus(status);
    }
    presence.addExtension(new MetaData(this.metaData));

    PacketCollector collector = this.connection.createPacketCollectorAndSend(new AndFilter(new StanzaTypeFilter(Presence.class),
            FromMatchesFilter.create(workgroupJID)), presence);

    collector.nextResultOrThrow();
}
项目:Smack    文件:Socks5TransferNegotiator.java   
@Override
InputStream negotiateIncomingStream(Stanza streamInitiation) throws InterruptedException,
                SmackException, XMPPErrorException {
    // build SOCKS5 Bytestream request
    Socks5BytestreamRequest request = new ByteStreamRequest(this.manager,
                    (Bytestream) streamInitiation);

    // always accept the request
    Socks5BytestreamSession session = request.accept();

    // test input stream
    try {
        PushbackInputStream stream = new PushbackInputStream(session.getInputStream());
        int firstByte = stream.read();
        stream.unread(firstByte);
        return stream;
    }
    catch (IOException e) {
        throw new SmackException("Error establishing input stream", e);
    }
}
项目:Smack    文件:BookmarkManager.java   
/**
 * Adds or updates a conference in the bookmarks.
 *
 * @param name the name of the conference
 * @param jid the jid of the conference
 * @param isAutoJoin whether or not to join this conference automatically on login
 * @param nickname the nickname to use for the user when joining the conference
 * @param password the password to use for the user when joining the conference
 * @throws XMPPErrorException thrown when there is an issue retrieving the current bookmarks from
 * the server.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException 
 */
public void addBookmarkedConference(String name, String jid, boolean isAutoJoin,
        String nickname, String password) throws NoResponseException, XMPPErrorException, NotConnectedException
{
    retrieveBookmarks();
    BookmarkedConference bookmark
            = new BookmarkedConference(name, jid, isAutoJoin, nickname, password);
    List<BookmarkedConference> conferences = bookmarks.getBookmarkedConferences();
    if(conferences.contains(bookmark)) {
        BookmarkedConference oldConference = conferences.get(conferences.indexOf(bookmark));
        if(oldConference.isShared()) {
            throw new IllegalArgumentException("Cannot modify shared bookmark");
        }
        oldConference.setAutoJoin(isAutoJoin);
        oldConference.setName(name);
        oldConference.setNickname(nickname);
        oldConference.setPassword(password);
    }
    else {
        bookmarks.addBookmarkedConference(bookmark);
    }
    privateDataManager.setPrivateData(bookmarks);
}
项目:Camel    文件:XmppEndpoint.java   
public String resolveRoom(XMPPConnection connection) throws XMPPException, SmackException {
    ObjectHelper.notEmpty(room, "room");

    if (room.indexOf('@', 0) != -1) {
        return room;
    }

    Iterator<String> iterator = MultiUserChat.getServiceNames(connection).iterator();
    if (!iterator.hasNext()) {
        throw new XMPPErrorException("Cannot find Multi User Chat service",
                                     new XMPPError(new XMPPError.Condition("Cannot find Multi User Chat service on connection: " + getConnectionMessage(connection))));
    }

    String chatServer = iterator.next();
    LOG.debug("Detected chat server: {}", chatServer);

    return room + "@" + chatServer;
}
项目: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    文件:PrivacyListManager.java   
/**
 * Answer the default privacy list. Returns <code>null</code> if there is no default list.
 * 
 * @return the privacy list of the default list.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */ 
public PrivacyList getDefaultList() throws NoResponseException, XMPPErrorException, NotConnectedException {
    Privacy privacyAnswer = this.getPrivacyWithListNames();
    String listName = privacyAnswer.getDefaultName();
    if (StringUtils.isNullOrEmpty(listName)) {
        return null;
    }
    boolean isDefaultAndActive = listName.equals(privacyAnswer.getActiveName());
    return new PrivacyList(isDefaultAndActive, true, listName, getPrivacyListItems(listName));
}
项目:Smack    文件:PrivacyListManager.java   
/**
 * Remove a privacy list.
 * 
    * @param listName the list that has changed its content.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */ 
public void deletePrivacyList(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException {
    // The request of the list is an privacy message with an empty list
    Privacy request = new Privacy();
    request.setPrivacyList(listName, new ArrayList<PrivacyItem>());

    // Send the package to the server
    setRequest(request);
}
项目:Smack    文件:Agent.java   
/**
 * Return the agents name.
 *
 * @return - the agents name.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public String getName() throws NoResponseException, XMPPErrorException, NotConnectedException {
    AgentInfo agentInfo = new AgentInfo();
    agentInfo.setType(IQ.Type.get);
    agentInfo.setTo(workgroupJID);
    agentInfo.setFrom(getUser());
    AgentInfo response = (AgentInfo) connection.createPacketCollectorAndSend(agentInfo).nextResultOrThrow();
    return response.getName();
}
项目:Smack    文件:AccountManager.java   
/**
 * Changes the password of the currently logged-in account. This operation can only
 * be performed after a successful login operation has been completed. Not all servers
 * support changing passwords; an XMPPException will be thrown when that is the case.
 *
 * @throws IllegalStateException if not currently logged-in to the server.
 * @throws XMPPErrorException if an error occurs when changing the password.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException 
 */
public void changePassword(String newPassword) throws NoResponseException, XMPPErrorException, NotConnectedException {
    if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) {
        // TODO throw exception in newer Smack versions
        LOGGER.warning("Changing password over insecure connection. "
                        + "This will throw an exception in future versions of Smack if AccountManager.sensitiveOperationOverInsecureConnection(true) is not set");
    }
    Map<String, String> map = new HashMap<String, String>();
    map.put("username",XmppStringUtils.parseLocalpart(connection().getUser()));
    map.put("password",newPassword);
    Registration reg = new Registration(map);
    reg.setType(IQ.Type.set);
    reg.setTo(connection().getServiceName());
    createPacketCollectorAndSend(reg).nextResultOrThrow();
}
项目:Smack    文件:PrivacyListManager.java   
/**
 * Client declines the use of active lists.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */ 
public void declineActiveList() throws NoResponseException, XMPPErrorException, NotConnectedException {
    // The request of the list is an privacy message with an empty list
    Privacy request = new Privacy();
    request.setDeclineActiveList(true);

    // Send the package to the server
    setRequest(request);
}
项目:Smack    文件:AgentSession.java   
/**
 * Asks the workgroup for it's Global Macros.
 *
 * @param global true to retrieve global macros, otherwise false for personal macros.
 * @return MacroGroup the root macro group.
 * @throws XMPPErrorException if an error occurs while getting information from the server.
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public MacroGroup getMacros(boolean global) throws NoResponseException, XMPPErrorException, NotConnectedException {
    Macros request = new Macros();
    request.setType(IQ.Type.get);
    request.setTo(workgroupJID);
    request.setPersonal(!global);

    Macros response = (Macros) connection.createPacketCollectorAndSend(request).nextResultOrThrow();
    return response.getRootGroup();
}
项目:Smack    文件:ServiceDiscoveryManager.java   
/**
 * Returns the discovered information of a given XMPP entity addressed by its JID.
 * Use null as entityID to query the server
 * 
 * @param entityID the address of the XMPP entity or null.
 * @return the discovered information.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public DiscoverInfo discoverInfo(String entityID) throws NoResponseException, XMPPErrorException, NotConnectedException {
    if (entityID == null)
        return discoverInfo(null, null);

    // Check if the have it cached in the Entity Capabilities Manager
    DiscoverInfo info = EntityCapsManager.getDiscoverInfoByUser(entityID);

    if (info != null) {
        // We were able to retrieve the information from Entity Caps and
        // avoided a disco request, hurray!
        return info;
    }

    // Try to get the newest node#version if it's known, otherwise null is
    // returned
    EntityCapsManager.NodeVerHash nvh = EntityCapsManager.getNodeVerHashByJid(entityID);

    // Discover by requesting the information from the remote entity
    // Note that wee need to use NodeVer as argument for Node if it exists
    info = discoverInfo(entityID, nvh != null ? nvh.getNodeVer() : null);

    // If the node version is known, store the new entry.
    if (nvh != null) {
        if (EntityCapsManager.verifyDiscoverInfoVersion(nvh.getVer(), nvh.getHash(), info))
            EntityCapsManager.addDiscoverInfoByNode(nvh.getNodeVer(), info);
    }

    return info;
}
项目:Smack    文件:PrivacyListManager.java   
/**
 * Answer the privacy list items under listName with the allowed and blocked permissions.
 * 
 * @param listName the name of the list to get the allowed and blocked permissions.
 * @return a list of privacy items under the list listName.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */ 
private List<PrivacyItem> getPrivacyListItems(String listName) throws NoResponseException, XMPPErrorException, NotConnectedException  {
    assert StringUtils.isNotEmpty(listName);
    // The request of the list is an privacy message with an empty list
    Privacy request = new Privacy();
    request.setPrivacyList(listName, new ArrayList<PrivacyItem>());

    // Send the package to the server and get the answer
    Privacy privacyAnswer = getRequest(request);

    return privacyAnswer.getPrivacyList(listName);
}
项目:Smack    文件:Workgroup.java   
/**
 * Asks the workgroup for it's Sound Settings.
 *
 * @return soundSettings the sound settings for the specified workgroup.
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public SoundSettings getSoundSettings() throws NoResponseException, XMPPErrorException, NotConnectedException {
    SoundSettings request = new SoundSettings();
    request.setType(IQ.Type.get);
    request.setTo(workgroupJID);

    SoundSettings response = (SoundSettings) connection.createPacketCollectorAndSend(request).nextResultOrThrow();
    return response;
}
项目:Smack    文件:RosterGroup.java   
/**
 * Adds a roster entry to this group. If the entry was unfiled then it will be removed from 
 * the unfiled list and will be added to this group.
 * Note that this is a synchronous call -- Smack must wait for the server
 * to receive the updated roster.
 *
 * @param entry a roster entry.
 * @throws XMPPErrorException if an error occured while trying to add the entry to the group.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException 
 */
public void addEntry(RosterEntry entry) throws NoResponseException, XMPPErrorException, NotConnectedException {
    // Only add the entry if it isn't already in the list.
    synchronized (entries) {
        if (!entries.contains(entry)) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.set);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.addGroupName(getName());
            packet.addRosterItem(item);
            // Wait up to a certain number of seconds for a reply from the server.
            connection().createPacketCollectorAndSend(packet).nextResultOrThrow();
        }
    }
}
项目:Smack    文件:Socks5ByteStreamRequestTest.java   
/**
 * Accepting a SOCKS5 Bytestream request should fail if target is not able to connect to any of
 * the provided SOCKS5 proxies.
 * 
 * @throws Exception
 */
@Test
public void shouldFailIfRequestHasInvalidStreamHosts() throws Exception {

    try {

        // build SOCKS5 Bytestream initialization request
        Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
                        initiatorJID, targetJID, sessionID);
        // add proxy that is not running
        bytestreamInitialization.addStreamHost(proxyJID, proxyAddress, 7778);

        // get SOCKS5 Bytestream manager for connection
        Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);

        // build SOCKS5 Bytestream request with the bytestream initialization
        Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
                        byteStreamManager, bytestreamInitialization);

        // accept the stream (this is the call that is tested here)
        byteStreamRequest.accept();

        fail("exception should be thrown");
    }
    catch (XMPPErrorException e) {
        assertTrue(e.getMessage().contains("Could not establish socket with any provided host"));
    }

    // verify targets response
    assertEquals(1, protocol.getRequests().size());
    Stanza targetResponse = protocol.getRequests().remove(0);
    assertTrue(IQ.class.isInstance(targetResponse));
    assertEquals(initiatorJID, targetResponse.getTo());
    assertEquals(IQ.Type.error, ((IQ) targetResponse).getType());
    assertEquals(XMPPError.Condition.item_not_found,
                    ((IQ) targetResponse).getError().getCondition());

}
项目:Smack    文件:PubSubManager.java   
/**
 * Creates an instant node, if supported.
 * 
 * @return The node that was created
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 */
public LeafNode createNode() throws NoResponseException, XMPPErrorException, NotConnectedException
{
    PubSub reply = sendPubsubPacket(Type.set, new NodeExtension(PubSubElementType.CREATE), null);
    NodeExtension elem = reply.getExtension("create", PubSubNamespace.BASIC.getXmlns());

    LeafNode newNode = new LeafNode(con, elem.getNode());
    newNode.setTo(to);
    nodeMap.put(newNode.getId(), newNode);

    return newNode;
}
项目:Smack    文件:VCardManager.java   
/**
 * Save this vCard for the user connected by 'connection'. XMPPConnection should be authenticated
 * and not anonymous.
 *
 * @throws XMPPErrorException thrown if there was an issue setting the VCard in the server.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException 
 */
public void saveVCard(VCard vcard) throws NoResponseException, XMPPErrorException, NotConnectedException {
    // XEP-54 § 3.2 "A user may publish or update his or her vCard by sending an IQ of type "set" with no 'to' address…"
    vcard.setTo(null);
    vcard.setType(IQ.Type.set);
    // Also make sure to generate a new stanza id (the given vcard could be a vcard result), in which case we don't
    // want to use the same stanza id again (although it wouldn't break if we did)
    vcard.setStanzaId(StanzaIdUtil.newStanzaId());
    connection().createPacketCollectorAndSend(vcard).nextResultOrThrow();
}
项目:Smack    文件:MultiUserChat.java   
private void changeAffiliationByAdmin(Collection<String> jids, MUCAffiliation affiliation)
                throws NoResponseException, XMPPErrorException, NotConnectedException {
    MUCAdmin iq = new MUCAdmin();
    iq.setTo(room);
    iq.setType(IQ.Type.set);
    for (String jid : jids) {
        // Set the new affiliation.
        MUCItem item = new MUCItem(affiliation, jid);
        iq.addItem(item);
    }

    connection.createPacketCollectorAndSend(iq).nextResultOrThrow();
}
项目:Smack    文件:Socks5ByteStreamRequestTest.java   
/**
 * Accepting a SOCKS5 Bytestream request should fail if the request doesn't contain any Socks5
 * proxies.
 * 
 * @throws Exception should not happen
 */
@Test
public void shouldFailIfRequestHasNoStreamHosts() throws Exception {

    try {

        // build SOCKS5 Bytestream initialization request with no SOCKS5 proxies
        Bytestream bytestreamInitialization = Socks5PacketUtils.createBytestreamInitiation(
                        initiatorJID, targetJID, sessionID);

        // get SOCKS5 Bytestream manager for connection
        Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);

        // build SOCKS5 Bytestream request with the bytestream initialization
        Socks5BytestreamRequest byteStreamRequest = new Socks5BytestreamRequest(
                        byteStreamManager, bytestreamInitialization);

        // accept the stream (this is the call that is tested here)
        byteStreamRequest.accept();

        fail("exception should be thrown");
    }
    catch (XMPPErrorException e) {
        assertTrue(e.getMessage().contains("Could not establish socket with any provided host"));
    }

    // verify targets response
    assertEquals(1, protocol.getRequests().size());
    Stanza targetResponse = protocol.getRequests().remove(0);
    assertTrue(IQ.class.isInstance(targetResponse));
    assertEquals(initiatorJID, targetResponse.getTo());
    assertEquals(IQ.Type.error, ((IQ) targetResponse).getType());
    assertEquals(XMPPError.Condition.item_not_found,
                    ((IQ) targetResponse).getError().getCondition());

}
项目:Smack    文件:LeafNode.java   
@SuppressWarnings("unchecked")
private <T extends Item> List<T> getItems(PubSub request,
                List<ExtensionElement> returnedExtensions) throws NoResponseException,
                XMPPErrorException, NotConnectedException {
    PubSub result = con.createPacketCollectorAndSend(request).nextResultOrThrow();
    ItemsExtension itemsElem = result.getExtension(PubSubElementType.ITEMS);
    if (returnedExtensions != null) {
        returnedExtensions.addAll(result.getExtensions());
    }
    return (List<T>) itemsElem.getItems();
}
项目:Smack    文件:InBandBytestreamManager.java   
/**
 * Establishes an In-Band Bytestream with the given user using the given session ID and returns
 * the session to send/receive data to/from the user.
 * 
 * @param targetJID the JID of the user an In-Band Bytestream should be established
 * @param sessionID the session ID for the In-Band Bytestream request
 * @return the session to send/receive data to/from the user
 * @throws XMPPErrorException if the user doesn't support or accept in-band bytestreams, or if the
 *         user prefers smaller block sizes
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException 
 */
public InBandBytestreamSession establishSession(String targetJID, String sessionID)
                throws NoResponseException, XMPPErrorException, NotConnectedException {
    Open byteStreamRequest = new Open(sessionID, this.defaultBlockSize, this.stanza);
    byteStreamRequest.setTo(targetJID);

    // sending packet will throw exception on timeout or error reply
    connection.createPacketCollectorAndSend(byteStreamRequest).nextResultOrThrow();

    InBandBytestreamSession inBandBytestreamSession = new InBandBytestreamSession(
                    this.connection, byteStreamRequest, targetJID);
    this.sessions.put(sessionID, inBandBytestreamSession);

    return inBandBytestreamSession;
}
项目:Smack    文件:IBBTransferNegotiator.java   
public InputStream createIncomingStream(StreamInitiation initiation)
                throws NoResponseException, XMPPErrorException, NotConnectedException {
    /*
     * In-Band Bytestream initiation listener must ignore next in-band bytestream request with
     * given session ID
     */
    this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());

    Stanza streamInitiation = initiateIncomingStream(this.connection, initiation);
    return negotiateIncomingStream(streamInitiation);
}
项目: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    文件:AbstractXMPPConnection.java   
@Override
public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter,
                final StanzaListener callback, final ExceptionCallback exceptionCallback,
                long timeout) throws NotConnectedException {
    Objects.requireNonNull(stanza, "stanza must not be null");
    // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we
    // disallow it here in the async API as it makes no sense
    Objects.requireNonNull(replyFilter, "replyFilter must not be null");
    Objects.requireNonNull(callback, "callback must not be null");

    final StanzaListener packetListener = new StanzaListener() {
        @Override
        public void processPacket(Stanza packet) throws NotConnectedException {
            try {
                XMPPErrorException.ifHasErrorThenThrow(packet);
                callback.processPacket(packet);
            }
            catch (XMPPErrorException e) {
                if (exceptionCallback != null) {
                    exceptionCallback.processException(e);
                }
            }
            finally {
                removeAsyncStanzaListener(this);
            }
        }
    };
    removeCallbacksService.schedule(new Runnable() {
        @Override
        public void run() {
            boolean removed = removeAsyncStanzaListener(packetListener);
            // If the packetListener got removed, then it was never run and
            // we never received a response, inform the exception callback
            if (removed && exceptionCallback != null) {
                exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter));
            }
        }
    }, timeout, TimeUnit.MILLISECONDS);
    addAsyncStanzaListener(packetListener, replyFilter);
    sendStanza(stanza);
}
项目:Smack    文件:OutgoingFileTransfer.java   
/**
 * This method handles the stream negotiation process and transmits the file
 * to the remote user. It returns immediately and the progress of the file
 * transfer can be monitored through several methods:
 *
 * <UL>
 * <LI>{@link FileTransfer#getStatus()}
 * <LI>{@link FileTransfer#getProgress()}
 * <LI>{@link FileTransfer#isDone()}
 * </UL>
 *
    * @param in the stream to transfer to the remote entity.
    * @param fileName the name of the file that is transferred
    * @param fileSize the size of the file that is transferred
    * @param description a description for the file to transfer.
 */
public synchronized void sendStream(final InputStream in, final String fileName, final long fileSize, final String description){
    checkTransferThread();

    setFileInfo(fileName, fileSize);
    transferThread = new Thread(new Runnable() {
        public void run() {
               //Create packet filter
               try {
                outputStream = negotiateStream(fileName, fileSize, description);
            } catch (XMPPErrorException e) {
                handleXMPPException(e);
                return;
            }
               catch (Exception e) {
                   setException(e);
               }
            if (outputStream == null) {
                return;
            }

               if (!updateStatus(Status.negotiated, Status.in_progress)) {
                return;
            }
            try {
                writeToStream(in, outputStream);
            } catch (IOException e) {
                setStatus(FileTransfer.Status.error);
                setException(e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }

                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                       /* Do Nothing */
                }
            }
               updateStatus(Status.in_progress, FileTransfer.Status.complete);
            }

    }, "File Transfer " + streamID);
    transferThread.start();
}
项目:Smack    文件:OutgoingFileTransfer.java   
/**
 * This method handles the stream negotiation process and transmits the file
 * to the remote user. It returns immediately and the progress of the file
 * transfer can be monitored through several methods:
 *
 * <UL>
 * <LI>{@link FileTransfer#getStatus()}
 * <LI>{@link FileTransfer#getProgress()}
 * <LI>{@link FileTransfer#isDone()}
 * </UL>
 *
    * @param file the file to transfer to the remote entity.
    * @param description a description for the file to transfer.
 * @throws SmackException
 *             If there is an error during the negotiation process or the
 *             sending of the file.
 */
public synchronized void sendFile(final File file, final String description)
        throws SmackException {
    checkTransferThread();
    if (file == null || !file.exists() || !file.canRead()) {
        throw new IllegalArgumentException("Could not read file");
    } else {
        setFileInfo(file.getAbsolutePath(), file.getName(), file.length());
    }

    transferThread = new Thread(new Runnable() {
        public void run() {
            try {
                outputStream = negotiateStream(file.getName(), file
                        .length(), description);
            } catch (XMPPErrorException e) {
                handleXMPPException(e);
                return;
            }
               catch (Exception e) {
                   setException(e);
               }
            if (outputStream == null) {
                return;
            }

               if (!updateStatus(Status.negotiated, Status.in_progress)) {
                return;
            }

            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(file);
                writeToStream(inputStream, outputStream);
            } catch (FileNotFoundException e) {
                setStatus(FileTransfer.Status.error);
                setError(Error.bad_file);
                setException(e);
            } catch (IOException e) {
                setStatus(FileTransfer.Status.error);
                setException(e);
            } finally {
                    if (inputStream != null) {
                        try {
                               inputStream.close();
                           } catch (IOException e) {
                               LOGGER.log(Level.WARNING, "Closing input stream", e);
                           }
                    }

                    try {
                           outputStream.close();
                       } catch (IOException e) {
                           LOGGER.log(Level.WARNING, "Closing output stream", e);
                       }
            }
               updateStatus(Status.in_progress, FileTransfer.Status.complete);
            }

    }, "File Transfer " + streamID);
    transferThread.start();
}
项目:Smack    文件:VersionManager.java   
public boolean isSupported(String jid) throws NoResponseException, XMPPErrorException,
                NotConnectedException {
    return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid,
                    Version.NAMESPACE);
}
项目:Smack    文件:RemoteCommand.java   
@Override
public void cancel() throws NoResponseException, XMPPErrorException, NotConnectedException {
    executeAction(Action.cancel);
}
项目:Smack    文件:RemoteCommand.java   
@Override
public void next(Form form) throws NoResponseException, XMPPErrorException, NotConnectedException {
    executeAction(Action.next, form);
}
项目:Smack    文件:AMPManager.java   
private static boolean isFeatureSupportedByServer(XMPPConnection connection, String featureName, String node) throws NoResponseException, XMPPErrorException, NotConnectedException {
    return ServiceDiscoveryManager.getInstanceFor(connection).supportsFeature(node, featureName);
}
项目:Smack    文件:EntityTimeManager.java   
public boolean isTimeSupported(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException  {
    return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, Time.NAMESPACE);
}
项目:Smack    文件:LeafNode.java   
private <T extends Item> List<T> getItems(PubSub request) throws NoResponseException,
                XMPPErrorException, NotConnectedException {
    return getItems(request, null);
}
项目:Smack    文件:IBBTransferNegotiator.java   
public OutputStream createOutgoingStream(String streamID, String initiator,
                String target) throws NoResponseException, XMPPErrorException, NotConnectedException {
    InBandBytestreamSession session = this.manager.establishSession(target, streamID);
    session.setCloseBothStreamsEnabled(true);
    return session.getOutputStream();
}
项目:lider    文件:XMPPClientImpl.java   
/**
 * Create new user with the provided password.
 * 
 * @param username
 * @param password
 * @return true if user created successfully, false otherwise
 * @throws NotConnectedException
 * @throws XMPPErrorException
 * @throws NoResponseException
 */
public void createAccount(String username, String password)
        throws NoResponseException, XMPPErrorException, NotConnectedException {
    AccountManager.sensitiveOperationOverInsecureConnectionDefault(true);
    AccountManager accountManager = AccountManager.getInstance(connection);
    if (accountManager.supportsAccountCreation()) {
        accountManager.createAccount(username, password);
    }
}
项目:Smack    文件:CarbonManager.java   
/**
 * Notify server to change the carbons state. This method blocks
 * some time until the server replies to the IQ and returns true on
 * success.
 *
 * You should first check for support using isSupportedByServer().
 *
 * @param new_state whether carbons should be enabled or disabled
 * @throws XMPPErrorException 
 * @throws NoResponseException 
 * @throws NotConnectedException 
 *
 */
public synchronized void setCarbonsEnabled(final boolean new_state) throws NoResponseException,
                XMPPErrorException, NotConnectedException {
    if (enabled_state == new_state)
        return;

    IQ setIQ = carbonsEnabledIQ(new_state);

    connection().createPacketCollectorAndSend(setIQ).nextResultOrThrow();
    enabled_state = new_state;
}
项目:Smack    文件:PacketCollector.java   
/**
 * Polls to see if a stanza(/packet) is currently available and returns it, or
 * immediately returns <tt>null</tt> if no packets are currently in the
 * result queue.
 * <p>
 * Throws an XMPPErrorException in case the polled stanzas did contain an XMPPError.
 * </p>
 * 
 * @return the next available packet.
 * @throws XMPPErrorException in case an error response.
 */
public <P extends Stanza> P pollResultOrThrow() throws XMPPErrorException {
    P result = pollResult();
    if (result != null) {
        XMPPErrorException.ifHasErrorThenThrow(result);
    }
    return result;
}