/**
   * Returns an Iterator with all the offline <tt>Messages</tt> of the user. The returned offline
   * messages will not be deleted from the server. Use {@link #deleteMessages(java.util.List)} to
   * delete the messages.
   *
   * @return an Iterator with all the offline <tt>Messages</tt> of the user.
   * @throws XMPPException If the user is not allowed to make this request or the server does not
   *     support offline message retrieval.
   */
  public Iterator getMessages() throws XMPPException {
    List messages = new ArrayList();
    OfflineMessageRequest request = new OfflineMessageRequest();
    request.setFetch(true);
    // Filter packets looking for an answer from the server.
    PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
    PacketCollector response = connection.createPacketCollector(responseFilter);
    // Filter offline messages that were requested by this request
    PacketCollector messageCollector = connection.createPacketCollector(packetFilter);
    // Send the retrieval request to the server.
    connection.sendPacket(request);
    // Wait up to a certain number of seconds for a reply.
    IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    response.cancel();

    if (answer == null) {
      throw new XMPPException("No response from server.");
    } else if (answer.getError() != null) {
      throw new XMPPException(answer.getError());
    }

    // Collect the received offline messages
    Message message =
        (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    while (message != null) {
      messages.add(message);
      message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    }
    // Stop queuing offline messages
    messageCollector.cancel();
    return messages.iterator();
  }
Example #2
0
 /**
  * 注册
  *
  * @param account 注册帐号
  * @param password 注册密码
  * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
  */
 public String regist(String account, String password) {
   if (connection == null) return "0";
   Registration reg = new Registration();
   reg.setType(IQ.Type.SET);
   reg.setTo(connection.getServiceName());
   reg.setUsername(account); // 注意这里createAccount注册时,参数是username,不是jid,是“@”前面的部分。
   reg.setPassword(password);
   reg.addAttribute("android", "geolo_createUser_android"); // 这边addAttribute不能为空,否则出错。
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel(); // 停止请求results(是否成功的结果)
   if (result == null) {
     Log.e("Regist", "No response from server.");
     return "0";
   } else if (result.getType() == IQ.Type.RESULT) {
     return "1";
   } else { // if (result.getType() == IQ.Type.ERROR)
     if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
       Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString());
       return "2";
     } else {
       Log.e("Regist", "IQ.Type.ERROR: " + result.getError().toString());
       return "3";
     }
   }
 }
Example #3
0
  /**
   * Returns the discovered items of a given XMPP entity addressed by its JID and note attribute.
   * Use this message only when trying to query information which is not directly addressable.
   *
   * @param entityID the address of the XMPP entity.
   * @param node the attribute that supplements the 'jid' attribute.
   * @return the discovered items.
   * @throws XMPPException if the operation failed for some reason.
   */
  public DiscoverItems discoverItems(String entityID, String node) throws XMPPException {
    // Discover the entity's items
    DiscoverItems disco = new DiscoverItems();
    disco.setType(IQ.Type.GET);
    disco.setTo(entityID);
    disco.setNode(node);

    // Create a packet collector to listen for a response.
    PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(disco.getPacketID()));

    connection.sendPacket(disco);

    // Wait up to 5 seconds for a result.
    IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
      throw new XMPPException("No response from the server.");
    }
    if (result.getType() == IQ.Type.ERROR) {
      throw new XMPPException(result.getError());
    }
    return (DiscoverItems) result;
  }
  /**
   * Returns an Iterator with the offline <tt>Messages</tt> whose stamp matches the specified
   * request. The request will include the list of stamps that uniquely identifies the offline
   * messages to retrieve. The returned offline messages will not be deleted from the server. Use
   * {@link #deleteMessages(java.util.List)} to delete the messages.
   *
   * @param nodes the list of stamps that uniquely identifies offline message.
   * @return an Iterator with the offline <tt>Messages</tt> that were received as part of this
   *     request.
   * @throws XMPPException If the user is not allowed to make this request or the server does not
   *     support offline message retrieval.
   */
  public Iterator getMessages(final List nodes) throws XMPPException {
    List messages = new ArrayList();
    OfflineMessageRequest request = new OfflineMessageRequest();
    for (Iterator it = nodes.iterator(); it.hasNext(); ) {
      OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next());
      item.setAction("view");
      request.addItem(item);
    }
    // Filter packets looking for an answer from the server.
    PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
    PacketCollector response = connection.createPacketCollector(responseFilter);
    // Filter offline messages that were requested by this request
    PacketFilter messageFilter =
        new AndFilter(
            packetFilter,
            new PacketFilter() {
              public boolean accept(Packet packet) {
                OfflineMessageInfo info =
                    (OfflineMessageInfo) packet.getExtension("offline", namespace);
                return nodes.contains(info.getNode());
              }
            });
    PacketCollector messageCollector = connection.createPacketCollector(messageFilter);
    // Send the retrieval request to the server.
    connection.sendPacket(request);
    // Wait up to a certain number of seconds for a reply.
    IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    response.cancel();

    if (answer == null) {
      throw new XMPPException("No response from server.");
    } else if (answer.getError() != null) {
      throw new XMPPException(answer.getError());
    }

    // Collect the received offline messages
    Message message =
        (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    while (message != null) {
      messages.add(message);
      message = (Message) messageCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    }
    // Stop queuing offline messages
    messageCollector.cancel();
    return messages.iterator();
  }
  /**
   * Deletes all offline messages of the user.
   *
   * @throws XMPPException If the user is not allowed to make this request or the server does not
   *     support offline message retrieval.
   */
  public void deleteMessages() throws XMPPException {
    OfflineMessageRequest request = new OfflineMessageRequest();
    request.setPurge(true);
    // Filter packets looking for an answer from the server.
    PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
    PacketCollector response = connection.createPacketCollector(responseFilter);
    // Send the deletion request to the server.
    connection.sendPacket(request);
    // Wait up to a certain number of seconds for a reply.
    IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    response.cancel();

    if (answer == null) {
      throw new XMPPException("No response from server.");
    } else if (answer.getError() != null) {
      throw new XMPPException(answer.getError());
    }
  }
  /**
   * Deletes the specified list of offline messages. The request will include the list of stamps
   * that uniquely identifies the offline messages to delete.
   *
   * @param nodes the list of stamps that uniquely identifies offline message.
   * @throws XMPPException If the user is not allowed to make this request or the server does not
   *     support offline message retrieval.
   */
  public void deleteMessages(List nodes) throws XMPPException {
    OfflineMessageRequest request = new OfflineMessageRequest();
    for (Iterator it = nodes.iterator(); it.hasNext(); ) {
      OfflineMessageRequest.Item item = new OfflineMessageRequest.Item((String) it.next());
      item.setAction("remove");
      request.addItem(item);
    }
    // Filter packets looking for an answer from the server.
    PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
    PacketCollector response = connection.createPacketCollector(responseFilter);
    // Send the deletion request to the server.
    connection.sendPacket(request);
    // Wait up to a certain number of seconds for a reply.
    IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    response.cancel();

    if (answer == null) {
      throw new XMPPException("No response from server.");
    } else if (answer.getError() != null) {
      throw new XMPPException(answer.getError());
    }
  }
Example #7
0
 /**
  * Gets the account registration info from the server.
  *
  * @throws XMPPException if an error occurs.
  */
 private synchronized void getRegistrationInfo() throws XMPPException {
   Registration reg = new Registration();
   reg.setTo(connection.getServiceName());
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel();
   if (result == null) {
     throw new XMPPException("No response from server.");
   } else if (result.getType() == IQ.Type.ERROR) {
     throw new XMPPException(result.getError());
   } else {
     info = (Registration) result;
   }
 }
  /**
   * Send a request to another user to send them a file. The other user has the option of,
   * accepting, rejecting, or not responding to a received file transfer request.
   *
   * <p>If they accept, the packet will contain the other user's chosen stream type to send the file
   * across. The two choices this implementation provides to the other user for file transfer are <a
   * href="http://www.jabber.org/jeps/jep-0065.html">SOCKS5 Bytestreams</a>, which is the preferred
   * method of transfer, and <a href="http://www.jabber.org/jeps/jep-0047.html">In-Band
   * Bytestreams</a>, which is the fallback mechanism.
   *
   * <p>The other user may choose to decline the file request if they do not desire the file, their
   * client does not support JEP-0096, or if there are no acceptable means to transfer the file.
   *
   * <p>Finally, if the other user does not respond this method will return null after the specified
   * timeout.
   *
   * @param userID The userID of the user to whom the file will be sent.
   * @param streamID The unique identifier for this file transfer.
   * @param fileName The name of this file. Preferably it should include an extension as it is used
   *     to determine what type of file it is.
   * @param size The size, in bytes, of the file.
   * @param desc A description of the file.
   * @param responseTimeout The amount of time, in milliseconds, to wait for the remote user to
   *     respond. If they do not respond in time, this
   * @return Returns the stream negotiator selected by the peer.
   * @throws XMPPException Thrown if there is an error negotiating the file transfer.
   */
  public StreamNegotiator negotiateOutgoingTransfer(
      final String userID,
      final String streamID,
      final String fileName,
      final long size,
      final String desc,
      int responseTimeout)
      throws XMPPException {
    final StreamInitiation si = new StreamInitiation();
    si.setSesssionID(streamID);
    si.setMimeType(URLConnection.guessContentTypeFromName(fileName));

    final StreamInitiation.File siFile = new StreamInitiation.File(fileName, size);
    siFile.setDesc(desc);
    si.setFile(siFile);

    si.setFeatureNegotiationForm(createDefaultInitiationForm());

    si.setFrom(connection.getUser());
    si.setTo(userID);
    si.setType(IQ.Type.SET);

    final PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(si.getPacketID()));
    connection.sendPacket(si);
    final Packet siResponse = collector.nextResult(responseTimeout);
    collector.cancel();

    if (siResponse instanceof IQ) {
      final IQ iqResponse = (IQ) siResponse;
      if (iqResponse.getType().equals(IQ.Type.RESULT)) {
        final StreamInitiation response = (StreamInitiation) siResponse;
        return getOutgoingNegotiator(getStreamMethodField(response.getFeatureNegotiationForm()));

      } else if (iqResponse.getType().equals(IQ.Type.ERROR)) {
        throw new XMPPException(iqResponse.getError());
      } else {
        throw new XMPPException("File transfer response unreadable");
      }
    } else {
      return null;
    }
  }
Example #9
0
 /**
  * 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 XMPPException if an error occurs when changing the password.
  */
 public void changePassword(String newPassword) throws XMPPException {
   Registration reg = new Registration();
   reg.setType(IQ.Type.SET);
   reg.setTo(connection.getServiceName());
   Map<String, String> map = new HashMap<String, String>();
   map.put("username", StringUtils.parseName(connection.getUser()));
   map.put("password", newPassword);
   reg.setAttributes(map);
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel();
   if (result == null) {
     throw new XMPPException("No response from server.");
   } else if (result.getType() == IQ.Type.ERROR) {
     throw new XMPPException(result.getError());
   }
 }
  /**
   * Returns the collection that will contain the name of the shared groups where the user logged in
   * with the specified session belongs.
   *
   * @param connection connection to use to get the user's shared groups.
   * @return collection with the shared groups' name of the logged user.
   */
  public static List getSharedGroups(XMPPConnection connection) throws XMPPException {
    // Discover the shared groups of the logged user
    SharedGroupsInfo info = new SharedGroupsInfo();
    info.setType(IQ.Type.GET);

    // Create a packet collector to listen for a response.
    PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(info.getPacketID()));

    connection.sendPacket(info);

    // Wait up to 5 seconds for a result.
    IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    // Stop queuing results
    collector.cancel();
    if (result == null) {
      throw new XMPPException("No response from the server.");
    }
    if (result.getType() == IQ.Type.ERROR) {
      throw new XMPPException(result.getError());
    }
    return ((SharedGroupsInfo) result).getGroups();
  }
Example #11
0
 /**
  * Deletes the currently logged-in account from the server. This operation can only be performed
  * after a successful login operation has been completed. Not all servers support deleting
  * accounts; an XMPPException will be thrown when that is the case.
  *
  * @throws IllegalStateException if not currently logged-in to the server.
  * @throws XMPPException if an error occurs when deleting the account.
  */
 public void deleteAccount() throws XMPPException {
   if (!connection.isAuthenticated()) {
     throw new IllegalStateException("Must be logged in to delete a account.");
   }
   Registration reg = new Registration();
   reg.setType(IQ.Type.SET);
   reg.setTo(connection.getServiceName());
   Map<String, String> attributes = new HashMap<String, String>();
   // To delete an account, we add a single attribute, "remove", that is blank.
   attributes.put("remove", "");
   reg.setAttributes(attributes);
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel();
   if (result == null) {
     throw new XMPPException("No response from server.");
   } else if (result.getType() == IQ.Type.ERROR) {
     throw new XMPPException(result.getError());
   }
 }
Example #12
0
 /**
  * Creates a new account using the specified username, password and account attributes. The
  * attributes Map must contain only String name/value pairs and must also have values for all
  * required attributes.
  *
  * @param username the username.
  * @param password the password.
  * @param attributes the account attributes.
  * @throws XMPPException if an error occurs creating the account.
  * @see #getAccountAttributes()
  */
 public void createAccount(String username, String password, Map<String, String> attributes)
     throws XMPPException {
   if (!supportsAccountCreation()) {
     throw new XMPPException("Server does not support account creation.");
   }
   Registration reg = new Registration();
   reg.setType(IQ.Type.SET);
   reg.setTo(connection.getServiceName());
   attributes.put("username", username);
   attributes.put("password", password);
   reg.setAttributes(attributes);
   PacketFilter filter =
       new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
   PacketCollector collector = connection.createPacketCollector(filter);
   connection.sendPacket(reg);
   IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
   // Stop queuing results
   collector.cancel();
   if (result == null) {
     throw new XMPPException("No response from server.");
   } else if (result.getType() == IQ.Type.ERROR) {
     throw new XMPPException(result.getError());
   }
 }
 /**
  * An error has occurred.
  *
  * @throws XMPPException
  */
 public void eventError(IQ iq) throws XMPPException {
   triggerSessionClosedOnError(new XMPPException(iq.getError().getMessage()));
   super.eventError(iq);
 }
 /**
  * An error has occurred.
  *
  * @throws XMPPException
  */
 public void eventError(IQ iq) throws XMPPException {
   if (iq == null) return;
   triggerSessionClosedOnError(new XMPPException(iq.getError()));
   super.eventError(iq);
 }
  /*
   * (non-Javadoc)
   *
   * @see com.saic.uicds.xmpp.communications.CommandWithReply#waitForSuccessOrFailure()
   */
  public boolean waitForSuccessOrFailure() {

    boolean success = true;

    if (connection.isConnected() && result == null) {
      int seconds = connection.getWaitTimeInSeconds() * 1000;
      // System.out.println("+++++ wait " + connection.getWaitTimeInSeconds() +
      // " seconds +++++");
      // System.out.println("Waiting for "+packetID);

      result = (IQ) collector.nextResult(seconds);

      // Stop queuing results
      collector.cancel();

      if (result == null) {
        errorMessage = "No response from the server.";
        success = false;
      } else if (result.getType() == IQ.Type.ERROR) {
        xmppError = result.getError();
        if (result.getError() != null) {
          errorMessage = result.getError().getMessage();
          errorCondition = result.getError().getCondition();
          errorType = result.getError().getType();
          errorCode = result.getError().getCode();
        } else {
          errorMessage = null;
          errorCondition = "";
          errorCode = 0;
          errorType = XMPPError.Type.CANCEL;
        }
        if (errorMessage == null) {
          errorMessage = "NULL error message";
        }
        if (result.getError() != null) {
          PacketExtension pe = null;
          pe =
              result
                  .getError()
                  .getExtension("unsupported", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            unsupported = true;
            errorMessage += " - (action is unsupported by the server)";
          }
          pe =
              result
                  .getError()
                  .getExtension("payload-too-big", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            payloadTooBig = true;
            errorMessage += " - (payload is too big)";
          }
          pe =
              result
                  .getError()
                  .getExtension("invalid-payload", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            invalidPayload = true;
            errorMessage += " - (invalid payload)";
          }
          pe =
              result
                  .getError()
                  .getExtension("item-required", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            itemRequired = true;
            errorMessage += " - (item element is required for this node)";
          }
          pe =
              result
                  .getError()
                  .getExtension("payload-required", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            payloadRequired = true;
            errorMessage += " - (payload is required for this node)";
          }
          pe =
              result
                  .getError()
                  .getExtension("item-forbidden", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            itemForbidden = true;
            errorMessage += " - (cannot publish item to transient node)";
          }
          pe =
              result
                  .getError()
                  .getExtension("invalid-jid", "http://jabber.org/protocol/pubsub#errors");
          if (pe != null) {
            invalidJID = true;
            errorMessage += " - (the bare JID portions of the JIDs do not match)";
          }
        }

        success = false;
      } else {
        // Pull out the subscription id if applicable
        Matcher m = subidPattern.matcher(result.toXML());
        if (m.find()) {
          subscriptionID = m.group(1);
          // System.out.println("GOT subid " + subscriptionID);
        } else {
          // System.err.println("No subid in " + result.toXML());
        }
        // Collection<String> exts = result.getPropertyNames();
        // System.out.println(exts.size()+" EXTENSIONS in "+result.getType());
        // for (Object o : exts) {
        // String ex = (String)o;
        // if (ex != null) {
        // System.out.println("FOUND "+ex);
        // }
        // }
      }
    } else {
      success = false;
      // Stop queuing results
      collector.cancel();
    }

    return success;
  }