コード例 #1
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;
  }
コード例 #2
0
  /** Loads streamhost address and ports from the proxies on the local server. */
  private void initStreamHosts() {
    List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>();
    Iterator it = proxies.iterator();
    IQ query;
    PacketCollector collector;
    Bytestream response;
    while (it.hasNext()) {
      String jid = it.next().toString();
      query =
          new IQ() {
            public String getChildElementXML() {
              return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>";
            }
          };
      query.setType(IQ.Type.GET);
      query.setTo(jid);

      collector = connection.createPacketCollector(new PacketIDFilter(query.getPacketID()));
      connection.sendPacket(query);

      response = (Bytestream) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
      if (response != null) {
        streamHosts.addAll(response.getStreamHosts());
      }
      collector.cancel();
    }
    this.streamHosts = streamHosts;
  }
コード例 #3
0
ファイル: MultiUserChat.java プロジェクト: sheytoon/Salam
 private Presence enter$324fb5b(String nickname, long timeout)
     throws NotConnectedException, NoResponseException, XMPPErrorException {
   if (StringUtils.isNullOrEmpty(nickname)) {
     throw new IllegalArgumentException("Nickname must not be null or blank.");
   }
   Presence joinPresence = new Presence(Type.available);
   joinPresence.to = this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname;
   joinPresence.addExtension(new MUCInitialPresence());
   for (PacketInterceptor interceptPacket : this.presenceInterceptors) {
     interceptPacket.interceptPacket(joinPresence);
   }
   PacketCollector response =
       this.connection.createPacketCollector(
           new AndFilter(
               FromMatchesFilter.createFull(
                   this.room + MqttTopic.TOPIC_LEVEL_SEPARATOR + nickname),
               new PacketTypeFilter(Presence.class)));
   this.connection.sendPacket(joinPresence);
   Presence presence = (Presence) response.nextResultOrThrow(timeout);
   this.nickname = nickname;
   this.joined = true;
   List<String> rooms = (List) joinedRooms.get(this.connection);
   if (rooms == null) {
     rooms = new ArrayList();
     joinedRooms.put(this.connection, rooms);
   }
   rooms.add(this.room);
   return presence;
 }
コード例 #4
0
ファイル: SmackHelper.java プロジェクト: akalz/ASpark
 /**
  * 注册
  *
  * @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";
     }
   }
 }
コード例 #5
0
  @Override
  public synchronized void sendXmlMessage(User user, final XmlMessage xmlMessage) {
    if (!myUI.connectAndLogin(null)) {
      return;
    }

    final String threadId = getThreadId(user);
    final PacketCollector packetCollector =
        myFacade.getConnection().createPacketCollector(new ThreadFilter(threadId));
    doSendMessage(xmlMessage, user, threadId);

    if (xmlMessage.needsResponse()) {
      //noinspection HardCodedStringLiteral
      final Runnable responseWaiterRunnable =
          () -> {
            try {
              processResponse(xmlMessage, packetCollector);
            } finally {
              packetCollector.cancel();
            }
          };
      myIdeFacade.runOnPooledThread(responseWaiterRunnable);
    } else {
      packetCollector.cancel();
    }
  }
コード例 #6
0
  public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException {
    PacketCollector collector =
        connection.createPacketCollector(
            getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID()));

    connection.sendPacket(super.createInitiationAccept(initiation, getNamespaces()));

    ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2);
    CompletionService<InputStream> service =
        new ExecutorCompletionService<InputStream>(threadPoolExecutor);
    List<Future<InputStream>> futures = new ArrayList<Future<InputStream>>();
    InputStream stream = null;
    XMPPException exception = null;
    try {
      futures.add(service.submit(new NegotiatorService(collector)));
      futures.add(service.submit(new NegotiatorService(collector)));

      int i = 0;
      while (stream == null && i < futures.size()) {
        Future<InputStream> future;
        try {
          i++;
          future = service.poll(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
          continue;
        }

        if (future == null) {
          continue;
        }

        try {
          stream = future.get();
        } catch (InterruptedException e) {
          /* Do Nothing */
        } catch (ExecutionException e) {
          exception = new XMPPException(e.getCause());
        }
      }
    } finally {
      for (Future<InputStream> future : futures) {
        future.cancel(true);
      }
      collector.cancel();
      threadPoolExecutor.shutdownNow();
    }
    if (stream == null) {
      if (exception != null) {
        throw exception;
      } else {
        throw new XMPPException("File transfer negotiation failed.");
      }
    }

    return stream;
  }
コード例 #7
0
ファイル: Workgroup.java プロジェクト: noschinl/Smack
  /**
   * Returns true if the workgroup is available for receiving new requests. The workgroup will be
   * available only when agents are available for this workgroup.
   *
   * @return true if the workgroup is available for receiving new requests.
   * @throws XMPPException
   */
  public boolean isAvailable() throws XMPPException {
    Presence directedPresence = new Presence(Presence.Type.available);
    directedPresence.setTo(workgroupJID);
    PacketFilter typeFilter = new PacketTypeFilter(Presence.class);
    PacketFilter fromFilter = FromMatchesFilter.create(workgroupJID);
    PacketCollector collector =
        connection.createPacketCollector(new AndFilter(fromFilter, typeFilter));

    connection.sendPacket(directedPresence);

    Presence response = (Presence) collector.nextResultOrThrow();
    return Presence.Type.available == response.getType();
  }
コード例 #8
0
 public static Packet sendAndWait(XMPPConnection c, Packet p, long timeout) throws XMPPException {
   PacketCollector pc = c.createPacketCollector(new PacketIDFilter(p.getPacketID()));
   c.sendPacket(p);
   final Packet result;
   if (timeout == 0) {
     result = pc.nextResult();
   } else {
     result = pc.nextResult(timeout);
   }
   if (result == null)
     throw new XMPPException("Timeout occured waiting for response to id " + p.getPacketID());
   XMPPError error = result.getError();
   if (error != null) throw new XMPPException(error);
   return result;
 }
コード例 #9
0
 @SuppressWarnings("unchecked")
 private XMPPBean sendAndWaitForResult(B bean) {
   if (bean != null) {
     this.connection.sendPacket(new BeanIQAdapter(bean));
   }
   while (true) {
     BeanIQAdapter adapter = (BeanIQAdapter) (beanCollector.nextResult(timeout));
     XMPPBean resultBean = null;
     if (adapter != null) {
       if (adapter.getBean().getNamespace().equals(resultBeanPrototype.getNamespace())) {
         resultBean = (ResultBeanType) (adapter.getBean());
       } else {
         resultBean = (B) (adapter.getBean());
       }
     }
     if (adapter == null || resultBean == null) {
       if (retryCount >= maxRetries) {
         return null;
       } else {
         retryCount++;
         sendAndWaitForResult(bean);
       }
     } else if (resultBean.getId().equals(beanOut.getId())) {
       return resultBean;
     }
   }
 }
コード例 #10
0
  /**
   * 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();
  }
コード例 #11
0
 public InputStream call() throws Exception {
   Packet streamInitiation =
       collector.nextResult(SmackConfiguration.getPacketReplyTimeout() * 2);
   if (streamInitiation == null) {
     throw new XMPPException("No response from remote client");
   }
   StreamNegotiator negotiator = determineNegotiator(streamInitiation);
   return negotiator.negotiateIncomingStream(streamInitiation);
 }
コード例 #12
0
ファイル: AccountManager.java プロジェクト: yunsite/yuchbox
 /**
  * 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;
   }
 }
コード例 #13
0
  /**
   * 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());
    }
  }
コード例 #14
0
  /**
   * 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;
    }
  }
コード例 #15
0
  /**
   * Returns the last activity of a particular jid. If the jid is a full JID (i.e., a JID of the
   * form of 'user@host/resource') then the last activity is the idle time of that connected
   * resource. On the other hand, when the jid is a bare JID (e.g. 'user@host') then the last
   * activity is the lapsed time since the last logout or 0 if the user is currently logged in.
   * Moreover, when the jid is a server or component (e.g., a JID of the form 'host') the last
   * activity is the uptime.
   *
   * @param con the current XMPPConnection.
   * @param jid the JID of the user.
   * @return the LastActivity packet of the jid.
   * @throws XMPPException thrown if a server error has occured.
   */
  public static LastActivity getLastActivity(XMPPConnection con, String jid) throws XMPPException {
    LastActivity activity = new LastActivity();
    activity.setTo(jid);

    PacketCollector collector =
        con.createPacketCollector(new PacketIDFilter(activity.getPacketID()));
    con.sendPacket(activity);

    LastActivity response =
        (LastActivity) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());

    // Cancel the collector.
    collector.cancel();
    if (response == null) {
      throw new XMPPException("No response from server on status set.");
    }
    if (response.getError() != null) {
      throw new XMPPException(response.getError());
    }
    return response;
  }
コード例 #16
0
ファイル: AccountManager.java プロジェクト: yunsite/yuchbox
 /**
  * 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());
   }
 }
コード例 #17
0
ファイル: TranscriptManager.java プロジェクト: jfojfo/Chat
  /**
   * Returns the transcripts of a given user. The answer will contain the complete history of
   * conversations that a user had.
   *
   * @param userID the id of the user to get his conversations.
   * @param workgroupJID the JID of the workgroup that will process the request.
   * @return the transcripts of a given user.
   * @throws XMPPException if an error occurs while getting the information.
   */
  public Transcripts getTranscripts(String workgroupJID, String userID) throws XMPPException {
    Transcripts request = new Transcripts(userID);
    request.setTo(workgroupJID);
    PacketCollector collector =
        connection.createPacketCollector(new PacketIDFilter(request.getPacketID()));
    // Send the request
    connection.sendPacket(request);

    Transcripts response =
        (Transcripts) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());

    // Cancel the collector.
    collector.cancel();
    if (response == null) {
      throw new XMPPException("No response from server on status set.");
    }
    if (response.getError() != null) {
      throw new XMPPException(response.getError());
    }
    return response;
  }
コード例 #18
0
  /**
   * Sends enable or disable carbon packet to the server.
   *
   * @param enable if <tt>true</tt> sends enable packet otherwise sends disable packet.
   */
  private void enableDisableCarbon(final boolean enable) {
    IQ iq =
        new IQ() {

          @Override
          public String getChildElementXML() {
            return "<" + (enable ? "enable" : "disable") + " xmlns='urn:xmpp:carbons:2' />";
          }
        };

    Packet response = null;
    try {
      PacketCollector packetCollector =
          jabberProvider
              .getConnection()
              .createPacketCollector(new PacketIDFilter(iq.getPacketID()));
      iq.setFrom(jabberProvider.getOurJID());
      iq.setType(IQ.Type.SET);
      jabberProvider.getConnection().sendPacket(iq);
      response = packetCollector.nextResult(SmackConfiguration.getPacketReplyTimeout());

      packetCollector.cancel();
    } catch (Exception e) {
      logger.error("Failed to enable carbon.", e);
    }

    isCarbonEnabled = false;

    if (response == null) {
      logger.error("Failed to enable carbon. No response is received.");
    } else if (response.getError() != null) {
      logger.error("Failed to enable carbon: " + response.getError());
    } else if (!(response instanceof IQ) || !((IQ) response).getType().equals(IQ.Type.RESULT)) {
      logger.error("Failed to enable carbon. The response is not correct.");
    } else {
      isCarbonEnabled = true;
    }
  }
コード例 #19
0
ファイル: DummyConnection.java プロジェクト: randhika/Smack
  /**
   * Processes a packet through the installed packet collectors and listeners and letting them
   * examine the packet to see if they are a match with the filter.
   *
   * @param packet the packet to process.
   */
  public void processPacket(Packet packet) {
    if (packet == null) {
      return;
    }

    // Loop through all collectors and notify the appropriate ones.
    for (PacketCollector collector : getPacketCollectors()) {
      collector.processPacket(packet);
    }

    if (DEBUG_ENABLED) {
      System.out.println("[RECV]: " + packet.toXML());
    }

    // Deliver the incoming packet to listeners.
    for (ListenerWrapper listenerWrapper : recvListeners.values()) {
      try {
        listenerWrapper.notifyListener(packet);
      } catch (NotConnectedException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #20
0
  /**
   * 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());
    }
  }
コード例 #21
0
  /**
   * 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();
  }
コード例 #22
0
ファイル: AccountManager.java プロジェクト: yunsite/yuchbox
 /**
  * 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());
   }
 }
コード例 #23
0
ファイル: AccountManager.java プロジェクト: yunsite/yuchbox
 /**
  * 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());
   }
 }
コード例 #24
0
  /**
   * 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();
  }
コード例 #25
0
  private static void processResponse(XmlMessage xmlMessage, PacketCollector collector) {
    boolean gotResponse = false;

    while (!gotResponse) {

      Message response = (Message) collector.nextResult(RESPONSE_TIMEOUT);
      if (response == null) break;

      final Collection<PacketExtension> extensions = response.getExtensions();
      for (PacketExtension o : extensions) {
        if (o instanceof JDOMExtension) {
          JDOMExtension extension = (JDOMExtension) o;
          if (RESPONSE.equals(extension.getElement().getName())) {
            xmlMessage.processResponse(extension.getElement());
            gotResponse = true;
            break;
          }
        }
      }
    }
  }
コード例 #26
0
  /*
   * (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;
  }