예제 #1
0
  /**
   * Enables or disables the XHTML support on a given connection.
   *
   * <p>Before starting to send XHTML messages to a user, check that the user can handle XHTML
   * messages. Enable the XHTML support to indicate that this client handles XHTML messages.
   *
   * @param connection the connection where the service will be enabled or disabled
   * @param enabled indicates if the service will be enabled or disabled
   */
  public static synchronized void setServiceEnabled(Connection connection, boolean enabled) {
    if (isServiceEnabled(connection) == enabled) return;

    if (enabled) {
      ServiceDiscoveryManager.getInstanceFor(connection).addFeature(namespace);
    } else {
      ServiceDiscoveryManager.getInstanceFor(connection).removeFeature(namespace);
    }
  }
예제 #2
0
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   SmackConfiguration.setAutoEnableEntityCaps(true);
   con0 = getConnection(0);
   con1 = getConnection(1);
   ecm0 = EntityCapsManager.getInstanceFor(getConnection(0));
   ecm1 = EntityCapsManager.getInstanceFor(getConnection(1));
   sdm0 = ServiceDiscoveryManager.getInstanceFor(con0);
   sdm1 = ServiceDiscoveryManager.getInstanceFor(con1);
   letsAllBeFriends();
 }
예제 #3
0
  /** Creates a destination for a service that receives XMPP messages. */
  public Destination getDestination(EndpointInfo endpointInfo) throws IOException {
    // The node name is the full name of the service.
    String nodeName = endpointInfo.getService().getName().toString();
    pepProvider.registerPEPParserExtension(nodeName, soapProvider);

    PEPDestination dest = new PEPDestination(endpointInfo);

    try {
      XMPPConnection conn = destinationConnectionFactory.login(endpointInfo);

      // Advertise interest in receiving information.
      ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(conn);
      disco.addFeature(nodeName + "+notify");

      // Create destination.
      dest.setXmppConnection(conn);
      conn.addPacketListener(
          dest, new PacketExtensionFilter("event", "http://jabber.org/protocol/pubsub#event"));

    } catch (XMPPException e) {
      throw new IOException(e);
    }

    return dest;
  }
예제 #4
0
  private void browseItem(DiscoverItems.Item discoveredItem) {
    addAddress(discoveredItem.getEntityID());
    browsePanel.removeAll();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(con);
    DiscoverItems result;
    try {
      result = discoManager.discoverItems(discoveredItem.getEntityID());
    } catch (XMPPException e) {
      browsePanel.invalidate();
      browsePanel.validate();
      browsePanel.repaint();
      return;
    }

    Iterator<DiscoverItems.Item> discoverItems = result.getItems();
    List<Entity> list = new ArrayList<Entity>();

    while (discoverItems.hasNext()) {
      DiscoverItems.Item item = discoverItems.next();
      Entity entity = new Entity(item);
      browsePanel.add(entity);
      list.add(entity);
    }

    GraphicUtils.makeSameSize((JComponent[]) list.toArray(new JComponent[list.size()]));

    browsePanel.invalidate();
    browsePanel.validate();
    browsePanel.repaint();
  }
예제 #5
0
  /**
   * Registers a new command with this command manager, which is related to a connection. The
   * <tt>node</tt> is an unique identifier of that command for the connection related to this
   * command manager. The <tt>name</tt> is the human readeale name of the command. The
   * <tt>factory</tt> generates new instances of the command.
   *
   * @param node the unique identifier of the command.
   * @param name the human readable name of the command.
   * @param factory a factory to create new instances of the command.
   */
  public void registerCommand(String node, final String name, LocalCommandFactory factory) {
    AdHocCommandInfo commandInfo = new AdHocCommandInfo(node, name, connection.getUser(), factory);

    commands.put(node, commandInfo);
    // Set the NodeInformationProvider that will provide information about
    // the added command
    ServiceDiscoveryManager.getInstanceFor(connection)
        .setNodeInformationProvider(
            node,
            new NodeInformationProvider() {
              public List<DiscoverItems.Item> getNodeItems() {
                return null;
              }

              public List<String> getNodeFeatures() {
                List<String> answer = new ArrayList<String>();
                answer.add(DISCO_NAMESPACE);
                // TODO: check if this service is provided by the
                // TODO: current connection.
                answer.add("jabber:x:data");
                return answer;
              }

              public List<DiscoverInfo.Identity> getNodeIdentities() {
                List<DiscoverInfo.Identity> answer = new ArrayList<DiscoverInfo.Identity>();
                DiscoverInfo.Identity identity = new DiscoverInfo.Identity("automation", name);
                identity.setType("command-node");
                answer.add(identity);
                return answer;
              }
            });
  }
예제 #6
0
  private void browse(String serviceName) {
    browsePanel.removeAll();

    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(con);
    DiscoverItems result;
    try {
      result = discoManager.discoverItems(serviceName);
    } catch (XMPPException e) {
      Log.error(e);
      return;
    }

    addAddress(serviceName);

    Iterator<DiscoverItems.Item> discoverItems = result.getItems();
    while (discoverItems.hasNext()) {
      DiscoverItems.Item item = discoverItems.next();
      Entity entity = new Entity(item);
      browsePanel.add(entity);
    }

    browsePanel.invalidate();
    browsePanel.validate();
    browsePanel.repaint();
  }
예제 #7
0
  private void initServiceDiscovery() {
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(extXMPPConnection);
    try {
      if (capsCacheDir == null) {
        capsCacheDir = new File(service.getCacheDir(), "entity-caps-cache");
        capsCacheDir.mkdirs();
        EntityCapsManager.setPersistentCache(new SimpleDirectoryPersistentCache(capsCacheDir));
      }
    } catch (java.io.IOException e) {
      Log.e(TAG, "Could not init : " + e.getLocalizedMessage());
    }

    PingManager.getInstanceFor(extXMPPConnection).setPingMinimumInterval(10 * 1000);
    String app_name = service.getString(R.string.app_name);
    String build_revision = service.getString(R.string.build_revision);
    Version.Manager.getInstanceFor(extXMPPConnection)
        .setVersion(new Version(app_name, build_revision, Constant.ANDROID));

    DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(extXMPPConnection);
    dm.enableAutoReceipts();
    dm.addReceiptReceivedListener(
        new ReceiptReceivedListener() { // DOES NOT WORK IN CARBONS
          public void onReceiptReceived(String fromJid, String toJid, String receiptId) {

            changeMessageDeliveryStatus(receiptId, ChatConstants.DS_ACKED);
          }
        });
  }
예제 #8
0
  private void initServiceDiscovery() {
    // register connection features
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mXMPPConnection);

    // init Entity Caps manager with storage in app's cache dir
    try {
      if (capsCacheDir == null) {
        capsCacheDir = new File(mService.getCacheDir(), "entity-caps-cache");
        capsCacheDir.mkdirs();
        EntityCapsManager.setPersistentCache(new SimpleDirectoryPersistentCache(capsCacheDir));
      }
    } catch (java.io.IOException e) {
      Log.e(TAG, "Could not init Entity Caps cache: " + e.getLocalizedMessage());
    }

    // reference PingManager, set ping flood protection to 10s
    PingManager.getInstanceFor(mXMPPConnection).setPingMinimumInterval(10 * 1000);

    // set Version for replies
    String app_name = mService.getString(org.yaxim.androidclient.R.string.app_name);
    String build_revision = mService.getString(org.yaxim.androidclient.R.string.build_revision);
    Version.Manager.getInstanceFor(mXMPPConnection)
        .setVersion(new Version(app_name, build_revision, "Android"));

    // reference DeliveryReceiptManager, add listener
    DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(mXMPPConnection);
    dm.enableAutoReceipts();
    dm.addReceiptReceivedListener(
        new ReceiptReceivedListener() { // DOES NOT WORK IN CARBONS
          public void onReceiptReceived(String fromJid, String toJid, String receiptId) {
            Log.d(TAG, "got delivery receipt for " + receiptId);
            changeMessageDeliveryStatus(receiptId, ChatConstants.DS_ACKED);
          }
        });
  }
예제 #9
0
 /**
  * Returns true if the specified user handles XHTML messages.
  *
  * @param connection the connection to use to perform the service discovery
  * @param userID the user to check. A fully qualified xmpp ID, e.g. [email protected]
  * @return a boolean indicating whether the specified user handles XHTML messages
  */
 public static boolean isServiceEnabled(Connection connection, String userID) {
   try {
     DiscoverInfo result = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(userID);
     return result.containsFeature(namespace);
   } catch (XMPPException e) {
     e.printStackTrace();
     return false;
   }
 }
예제 #10
0
 /**
  * Returns an iterator on <tt>OfflineMessageHeader</tt> that keep information about the offline
  * message. The OfflineMessageHeader includes a stamp that could be used to retrieve the complete
  * message or delete the specific message.
  *
  * @return an iterator on <tt>OfflineMessageHeader</tt> that keep information about the offline
  *     message.
  * @throws XMPPException If the user is not allowed to make this request or the server does not
  *     support offline message retrieval.
  */
 public Iterator getHeaders() throws XMPPException {
   List answer = new ArrayList();
   DiscoverItems items =
       ServiceDiscoveryManager.getInstanceFor(connection).discoverItems(null, namespace);
   for (Iterator it = items.getItems(); it.hasNext(); ) {
     DiscoverItems.Item item = (DiscoverItems.Item) it.next();
     answer.add(new OfflineMessageHeader(item));
   }
   return answer.iterator();
 }
예제 #11
0
 /**
  * Returns the number of offline messages for the user of the connection.
  *
  * @return the number of offline messages for the user of the connection.
  * @throws XMPPException If the user is not allowed to make this request or the server does not
  *     support offline message retrieval.
  */
 public int getMessageCount() throws XMPPException {
   DiscoverInfo info =
       ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(null, namespace);
   Form extendedInfo = Form.getFormFrom(info);
   if (extendedInfo != null) {
     String value = (String) extendedInfo.getField("number_of_messages").getValues().next();
     return Integer.parseInt(value);
   }
   return 0;
 }
예제 #12
0
 public boolean initFileTransport() {
   if (connection == null) {
     return false;
   } else if (fileTransferManager != null) {
     return true;
   } else {
     fileTransferManager = new FileTransferManager(connection);
     ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
     if (sdm == null) sdm = new ServiceDiscoveryManager(connection);
     sdm.addFeature("http://jabber.org/protocol/disco#info");
     sdm.addFeature("jabber:iq:privacy");
     FileTransferNegotiator.setServiceEnabled(connection, true);
     return true;
   }
 }
 /** Discover the features provided by the server. */
 private void discoverServerFeatures() {
   try {
     // jid et server
     ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mAdaptee);
     DiscoverInfo info = sdm.discoverInfo(mAdaptee.getServiceName());
     Iterator<DiscoverInfo.Identity> it = info.getIdentities();
     while (it.hasNext()) {
       DiscoverInfo.Identity identity = it.next();
       if ("pubsub".equals(identity.getCategory()) && "pep".equals(identity.getType())) {
         initPEP();
       }
     }
   } catch (XMPPException e) {
     Log.w(TAG, "Unable to discover server features", e);
   }
 }
예제 #14
0
 /**
  * Tries to discover if the server of the given XMPPConnection provides also a MUC component. Will
  * return the MUCs Component ID if one is found otherwise returns null
  *
  * @param connection
  * @return
  * @throws XMPPException
  */
 public static String disocverMUC(XMPPConnection connection) throws XMPPException {
   ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
   DiscoverItems ditem = sdm.discoverItems(connection.getServiceName());
   Iterator<Item> it = ditem.getItems();
   while (it.hasNext()) {
     Item i = it.next();
     DiscoverInfo dinfo = sdm.discoverInfo(i.getEntityID());
     Iterator<Feature> itFeatures = dinfo.getFeatures();
     while (itFeatures.hasNext()) {
       Feature f = itFeatures.next();
       if (f.getVar().equals(MUC_FEATURE)) {
         return i.getEntityID();
       }
     }
   }
   return null;
 }
예제 #15
0
  /**
   * Publish the commands to an specific JID.
   *
   * @param jid the full JID to publish the commands to.
   * @throws XMPPException if the operation failed for some reason.
   */
  public void publishCommands(String jid) throws XMPPException {
    ServiceDiscoveryManager serviceDiscoveryManager =
        ServiceDiscoveryManager.getInstanceFor(connection);

    // Collects the commands to publish as items
    DiscoverItems discoverItems = new DiscoverItems();
    Collection<AdHocCommandInfo> xCommandsList = getRegisteredCommands();

    for (AdHocCommandInfo info : xCommandsList) {
      DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID());
      item.setName(info.getName());
      item.setNode(info.getNode());
      discoverItems.addItem(item);
    }

    serviceDiscoveryManager.publishItems(jid, discoNode, discoverItems);
  }
  /**
   * Checks to see if all file transfer related services are enabled on the connection.
   *
   * @param connection The connection to check
   * @return True if all related services are enabled, false if they are not.
   */
  public static boolean isServiceEnabled(final Connection connection) {
    final ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(connection);

    final List<String> namespaces = new ArrayList<String>();
    namespaces.addAll(Arrays.asList(NAMESPACE));
    namespaces.add(InBandBytestreamManager.NAMESPACE);
    if (!IBB_ONLY) {
      namespaces.add(Socks5BytestreamManager.NAMESPACE);
    }

    for (final String namespace : namespaces) {
      if (!manager.includesFeature(namespace)) {
        return false;
      }
    }
    return true;
  }
예제 #17
0
  /**
   * Deletes the session agent account, frees all resources and disconnects the XMPP connection.
   *
   * @throws org.jivesoftware.smack.XMPPException
   */
  public void shutdown() throws XMPPException {
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection);

    // ServiceDiscovery (feature) http://rn.inf.tu-dresden.de/mobilis
    try {
      sdm.removeFeature(MobilisManager.discoNamespace);
    } catch (Exception e) {
      MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " + e.getMessage());
    }

    // ServiceDiscovery (info+items) http://rn.inf.tu-dresden.de/mobilis#services
    try {
      sdm.removeNodeInformationProvider(MobilisManager.discoServicesNode);
    } catch (Exception e) {
      MobilisManager.getLogger()
          .warning(
              "Problem with NodeInformationProvider: "
                  + MobilisManager.discoServicesNode
                  + " ("
                  + getIdent()
                  + ") "
                  + e.getMessage());
    }

    for (MobilisService service : mServices) {
      try {
        sdm.removeNodeInformationProvider(service.getNode());
        service.shutdown();
      } catch (Exception e) {
        // TODO Auto-generated catch block
      }
    }

    if ((mConnection != null) && mConnection.isConnected()) {
      mConnection.removeConnectionListener(this);
      mConnection.disconnect();
    }
    mConnection = null;

    // logging
    MobilisManager.getLogger().info("Mobilis Agent (" + getIdent() + ") shut down.");
  }
예제 #18
0
 private void populateFeatureSet() {
   final ServiceDiscoveryManager disco =
       ServiceDiscoveryManager.getInstanceFor(ChatsyManager.getConnection());
   final DiscoverItems items = ChatsyManager.getSessionManager().getDiscoveredItems();
   Iterator<DiscoverItems.Item> iter = items.getItems();
   while (iter.hasNext()) {
     DiscoverItems.Item item = iter.next();
     String entity = item.getEntityID();
     if (entity != null) {
       if (entity.startsWith("manager.")) {
         chatsyManagerInstalled = true;
         try {
           featureInfo = disco.discoverInfo(item.getEntityID());
         } catch (XMPPException e) {
           Log.error("Error while retrieving feature list for ChatsyManager.", e);
         }
       }
     }
   }
 }
예제 #19
0
 private boolean checkIfPrivacyIsSupported(XMPPConnection conn) {
   ServiceDiscoveryManager servDisc = ServiceDiscoveryManager.getInstanceFor(conn);
   DiscoverInfo info = null;
   try {
     String xmppHost = DNSUtil.resolveXMPPDomain(conn.getServiceName()).getHost();
     info = servDisc.discoverInfo(xmppHost);
   } catch (XMPPException e) {
     // We could not query the server
     return false;
   }
   if (info != null) {
     for (Iterator<Feature> i = info.getFeatures(); i.hasNext(); ) {
       String s = i.next().getVar();
       if (s.contains("jabber:iq:privacy")) {
         return true;
       }
     }
   }
   return false;
 }
  /**
   * Enable the Jabber services related to file transfer on the particular connection.
   *
   * @param connection The connection on which to enable or disable the services.
   * @param isEnabled True to enable, false to disable.
   */
  public static void setServiceEnabled(final Connection connection, final boolean isEnabled) {
    final ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(connection);

    final List<String> namespaces = new ArrayList<String>();
    namespaces.addAll(Arrays.asList(NAMESPACE));
    namespaces.add(InBandBytestreamManager.NAMESPACE);
    if (!IBB_ONLY) {
      namespaces.add(Socks5BytestreamManager.NAMESPACE);
    }

    for (final String namespace : namespaces) {
      if (isEnabled) {
        if (!manager.includesFeature(namespace)) {
          manager.addFeature(namespace);
        }
      } else {
        manager.removeFeature(namespace);
      }
    }
  }
 private void initProxies() {
   proxies = new ArrayList<String>();
   ServiceDiscoveryManager manager = ServiceDiscoveryManager.getInstanceFor(connection);
   try {
     DiscoverItems discoItems = manager.discoverItems(connection.getServiceName());
     Iterator it = discoItems.getItems();
     while (it.hasNext()) {
       DiscoverItems.Item item = (DiscoverItems.Item) it.next();
       String proxy = checkIsProxy(manager, item);
       if (proxy != null) {
         proxies.add(proxy);
       }
     }
   } catch (XMPPException e) {
     return;
   }
   if (proxies.size() > 0) {
     initStreamHosts();
   }
 }
  /** Initialize the features provided by beem. */
  private void initFeatures() {
    ServiceDiscoveryManager.setIdentityName("Beem");
    ServiceDiscoveryManager.setIdentityType("phone");
    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mAdaptee);
    if (sdm == null) sdm = new ServiceDiscoveryManager(mAdaptee);

    sdm.addFeature("http://jabber.org/protocol/disco#info");
    // nikita: must be uncommented when the feature will be enabled
    // sdm.addFeature("jabber:iq:privacy");
    sdm.addFeature("http://jabber.org/protocol/caps");
    sdm.addFeature("urn:xmpp:avatar:metadata");
    sdm.addFeature("urn:xmpp:avatar:metadata+notify");
    sdm.addFeature("urn:xmpp:avatar:data");
    sdm.addFeature("http://jabber.org/protocol/nick");
    sdm.addFeature("http://jabber.org/protocol/nick+notify");
    sdm.addFeature(PingExtension.NAMESPACE);

    mChatStateManager = ChatStateManager.getInstance(mAdaptee);
    BeemCapsManager caps = new BeemCapsManager(sdm, mAdaptee, mService);
    caps.setNode("http://www.beem-project.com");
  }
예제 #23
0
	private void initData() {
		try {
			/** 获取好友列表 */
			groupNames = ContacterManager.getGroupNames(XmppConnectionManager
					.getInstance().getConnection().getRoster());
			rGroups = ContacterManager.getGroups(XmppConnectionManager
					.getInstance().getConnection().getRoster());

			/** 获取聊天室列表 */
			Iterator<?> it = ServiceDiscoveryManager
					.getInstanceFor(
							XmppConnectionManager.getInstance().getConnection())
					.discoverItems("conference.wangxc").getItems();
			while (it.hasNext()) {
				DiscoverItems.Item item = (DiscoverItems.Item) it.next();
				chatRoomList.add(item);
				roomNames.add(item.getName());
			}
		} catch (Exception e) {
			groupNames = new ArrayList<String>();
			rGroups = new ArrayList<MRosterGroup>();
		}
	}
예제 #24
0
  /**
   * Perform a ServiceDiscovery [1] and check if the given resource is among the features supported
   * by the given recipient.
   *
   * <p>[1] XEP-0030 http://xmpp.org/extensions/xep-0030.html
   *
   * @param jid The JID must have a resource identifier (user@host/resource), otherwise you get a
   *     blame StackTrace in your logs.
   * @return DiscoverInfo from recipient or null if an XMPPException was thrown.
   * @blocking This method blocks until the ServiceDiscovery returns.
   * @reentrant This method can be called concurrently.
   * @nonCaching This method does not use a cache, but queries the server directly.
   */
  private DiscoverInfo performServiceDiscovery(final JID jid) {

    if (jid.isBareJID()) {
      LOG.warn(
          "cannot perform service discovery on a non resource qualified jid: " + jid.toString(),
          new StackTrace());
      return null;
    }

    final Connection connection = connectionService.getConnection();

    if (connection == null) {
      LOG.warn("cannot not perform a service discovery because not connected to a XMPP server");
      return null;
    }

    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);

    try {
      return sdm.discoverInfo(jid.toString());
    } catch (XMPPException e) {

      LOG.warn(
          "Service Discovery failed on recipient "
              + jid.toString()
              + " server: "
              + connection.getHost(),
          e);

      /*
       * FIXME handle timeouts and error conditions differently ! see
       * http://xmpp.org/extensions/xep-0030.html#errors
       */
      return null;
    }
  }
    @Override
    public void connectionCreated(XMPPConnection connection) {
      if (XMPPFriendConnectionImpl.this.connection != connection) {
        return;
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("connection created for " + connection.toString());
      }
      connection.addConnectionListener(this);

      synchronized (ProviderManager.getInstance()) {
        if (ProviderManager.getInstance().getIQProvider("address", "jabber:iq:lw-address")
            == null) {
          ProviderManager.getInstance()
              .addIQProvider(
                  "address", "jabber:iq:lw-address", new AddressIQProvider(addressFactory));
        }
        if (ProviderManager.getInstance()
                .getIQProvider("file-transfer", "jabber:iq:lw-file-transfer")
            == null) {
          ProviderManager.getInstance()
              .addIQProvider(
                  "file-transfer", "jabber:iq:lw-file-transfer", FileTransferIQ.getIQProvider());
        }
        if (ProviderManager.getInstance().getIQProvider("auth-token", "jabber:iq:lw-auth-token")
            == null) {
          ProviderManager.getInstance()
              .addIQProvider("auth-token", "jabber:iq:lw-auth-token", new AuthTokenIQProvider());
        }
        if (ProviderManager.getInstance()
                .getIQProvider("library-changed", "jabber:iq:lw-lib-change")
            == null) {
          ProviderManager.getInstance()
              .addIQProvider(
                  "library-changed", "jabber:iq:lw-lib-change", LibraryChangedIQ.getIQProvider());
        }
        if (ProviderManager.getInstance()
                .getIQProvider(ConnectBackRequestIQ.ELEMENT_NAME, ConnectBackRequestIQ.NAME_SPACE)
            == null) {
          ProviderManager.getInstance()
              .addIQProvider(
                  ConnectBackRequestIQ.ELEMENT_NAME,
                  ConnectBackRequestIQ.NAME_SPACE,
                  new ConnectBackRequestIQProvider());
        }
        if (ProviderManager.getInstance().getIQProvider(NoSaveIQ.ELEMENT_NAME, NoSaveIQ.NAME_SPACE)
            == null) {
          ProviderManager.getInstance()
              .addIQProvider(NoSaveIQ.ELEMENT_NAME, NoSaveIQ.NAME_SPACE, NoSaveIQ.getIQProvider());
        }
      }

      ChatStateManager.getInstance(connection);

      discoInfoListener =
          new DiscoInfoListener(XMPPFriendConnectionImpl.this, connection, featureRegistry);
      discoInfoListener.addListeners(connectionMulticaster, friendPresenceSupport);

      addressIQListener =
          addressIQListenerFactory.create(XMPPFriendConnectionImpl.this, addressFactory);
      connection.addPacketListener(addressIQListener, addressIQListener.getPacketFilter());

      fileTransferIQListener = fileTransferIQListenerFactory.create(XMPPFriendConnectionImpl.this);
      connection.addPacketListener(
          fileTransferIQListener, fileTransferIQListener.getPacketFilter());

      authTokenIQListener = authTokenIQListenerFactory.create(XMPPFriendConnectionImpl.this);
      connection.addPacketListener(authTokenIQListener, authTokenIQListener.getPacketFilter());

      libraryChangedIQListener =
          libraryChangedIQListenerFactory.create(XMPPFriendConnectionImpl.this);
      connection.addPacketListener(
          libraryChangedIQListener, libraryChangedIQListener.getPacketFilter());

      connectRequestIQListener =
          connectBackRequestIQListenerFactory.create(XMPPFriendConnectionImpl.this);
      connection.addPacketListener(
          connectRequestIQListener, connectRequestIQListener.getPacketFilter());

      new LimewireFeatureInitializer().register(featureRegistry);

      noSaveFeatureInitializer =
          new NoSaveFeatureInitializer(
              connection, XMPPFriendConnectionImpl.this, rosterListeners, friendPresenceSupport);
      noSaveFeatureInitializer.register(featureRegistry);

      SubscriptionListener sub = new SubscriptionListener(connection, friendRequestBroadcaster);
      connection.addPacketListener(sub, sub);

      for (URI feature : featureRegistry.getPublicFeatureUris()) {
        ServiceDiscoveryManager.getInstanceFor(connection).addFeature(feature.toASCIIString());
      }
      if (xmppActivityListener == null) {
        xmppActivityListener = new XmppActivityEventListener();
      }
      xmppActivitySupport.addListener(xmppActivityListener);

      if (idleStatusMonitor == null) {
        idleStatusMonitor = idleStatusMonitorFactory.create();
      }
      idleStatusMonitor.start();
    }
예제 #26
0
 /**
  * Discover the commands of an specific JID. The <code>jid</code> is a full JID.
  *
  * @param jid the full JID to retrieve the commands for.
  * @return the discovered items.
  * @throws XMPPException if the operation failed for some reason.
  */
 public DiscoverItems discoverCommands(String jid) throws XMPPException {
   ServiceDiscoveryManager serviceDiscoveryManager =
       ServiceDiscoveryManager.getInstanceFor(connection);
   return serviceDiscoveryManager.discoverItems(jid, discoNode);
 }
예제 #27
0
  /**
   *
   *
   * <ul>
   *   <li>Adds listeners to the connection
   *   <li>Registers the ad-hoc command feature to the ServiceDiscoveryManager
   *   <li>Registers the items of the feature
   *   <li>Adds packet listeners to handle execution requests
   *   <li>Creates and start the session sweeper
   * </ul>
   */
  private void init() {
    // Register the new instance and associate it with the connection
    synchronized (instances) {
      instances.put(connection, this);
    }

    // Add a listener to the connection that removes the registered instance
    // when the connection is closed
    connection.addConnectionListener(
        new ConnectionListener() {
          public void connectionClosed() {
            synchronized (instances) {
              instances.remove(connection);
            }
          }

          public void connectionClosedOnError(Exception e) {
            synchronized (instances) {
              instances.remove(connection);
            }
          }

          public void reconnectionSuccessful() {
            synchronized (instances) {
              instances.put(connection, AdHocCommandManager.this);
            }
          }

          public void reconnectingIn(int seconds) {}

          public void reconnectionFailed(Exception e) {}
        });

    // Add the feature to the service discovery manage to show that this
    // connection supports the AdHoc-Commands protocol.
    // This information will be used when another client tries to
    // discover whether this client supports AdHoc-Commands or not.
    ServiceDiscoveryManager.getInstanceFor(connection).addFeature(DISCO_NAMESPACE);

    // Set the NodeInformationProvider that will provide information about
    // which AdHoc-Commands are registered, whenever a disco request is
    // received
    ServiceDiscoveryManager.getInstanceFor(connection)
        .setNodeInformationProvider(
            discoNode,
            new NodeInformationProvider() {
              public List<DiscoverItems.Item> getNodeItems() {

                List<DiscoverItems.Item> answer = new ArrayList<DiscoverItems.Item>();
                Collection<AdHocCommandInfo> commandsList = getRegisteredCommands();

                for (AdHocCommandInfo info : commandsList) {
                  DiscoverItems.Item item = new DiscoverItems.Item(info.getOwnerJID());
                  item.setName(info.getName());
                  item.setNode(info.getNode());
                  answer.add(item);
                }

                return answer;
              }

              public List<String> getNodeFeatures() {
                return null;
              }

              public List<Identity> getNodeIdentities() {
                return null;
              }
            });

    // The packet listener and the filter for processing some AdHoc Commands
    // Packets
    PacketListener listener =
        new PacketListener() {
          public void processPacket(Packet packet) {
            AdHocCommandData requestData = (AdHocCommandData) packet;
            processAdHocCommand(requestData);
          }
        };

    PacketFilter filter = new PacketTypeFilter(AdHocCommandData.class);
    connection.addPacketListener(listener, filter);

    // Create a thread to reap sessions. But, we'll only start it later when commands are
    // actually registered.
    sessionsSweeper =
        new Thread(
            new Runnable() {
              public void run() {
                while (true) {
                  for (String sessionId : executingCommands.keySet()) {
                    LocalCommand command = executingCommands.get(sessionId);
                    // Since the command could be removed in the meanwhile
                    // of getting the key and getting the value - by a
                    // processed packet. We must check if it still in the
                    // map.
                    if (command != null) {
                      long creationStamp = command.getCreationDate();
                      // Check if the Session data has expired (default is
                      // 10 minutes)
                      // To remove it from the session list it waits for
                      // the double of the of time out time. This is to
                      // let
                      // the requester know why his execution request is
                      // not accepted. If the session is removed just
                      // after the time out, then whe the user request to
                      // continue the execution he will recieved an
                      // invalid session error and not a time out error.
                      if (System.currentTimeMillis() - creationStamp > SESSION_TIMEOUT * 1000 * 2) {
                        // Remove the expired session
                        executingCommands.remove(sessionId);
                      }
                    }
                  }
                  try {
                    Thread.sleep(1000);
                  } catch (InterruptedException ie) {
                    // Ignore.
                  }
                }
              }
            });
    sessionsSweeper.setDaemon(true);
  }
예제 #28
0
 /**
  * Returns true if the server supports Flexible Offline Message Retrieval. When the server
  * supports Flexible Offline Message Retrieval it is possible to get the header of the offline
  * messages, get specific messages, delete specific messages, etc.
  *
  * @return a boolean indicating if the server supports Flexible Offline Message Retrieval.
  * @throws XMPPException If the user is not allowed to make this request.
  */
 public boolean supportsFlexibleRetrieval() throws XMPPException {
   DiscoverInfo info = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(null);
   return info.containsFeature(namespace);
 }
예제 #29
0
  public void startup() throws XMPPException {
    String host;
    Integer port;
    String service;

    synchronized (mDefaultSettings) {
      host = (String) mDefaultSettings.get("host");
      port = Integer.parseInt((String) mDefaultSettings.get("port"));
      service = (String) mDefaultSettings.get("service");
    }

    ConnectionConfiguration connConfig = new ConnectionConfiguration(host, port, service);
    mConnection = new XMPPConnection(connConfig);
    mConnection.connect();

    String password = null;
    String resource = null;

    synchronized (mDefaultSettings) {
      mJid = mDefaultSettings.get("username") + "@" + mDefaultSettings.get("service");
      password = (String) mDefaultSettings.get("password");
      resource = (String) mDefaultSettings.get("resource");
    }

    mConnection.login(mJid, password, resource);
    mConnection.addConnectionListener(this);

    ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mConnection);

    // Set on every established connection that this client supports the Mobilis
    // protocol. This information will be used when another client tries to
    // discover whether this client supports Mobilis or not.
    try {
      sdm.addFeature(MobilisManager.discoNamespace);
    } catch (Exception e) {
      MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " + e.getMessage());
    }

    synchronized (mServices) {
      for (MobilisService ms : mServices) {
        try {
          ms.startup();
          sdm.setNodeInformationProvider(ms.getNode(), ms);
        } catch (Exception e) {
          MobilisManager.getLogger()
              .warning(
                  "Couldn't startup Mobilis Service ("
                      + ms.getIdent()
                      + ") because of "
                      + e.getClass().getName()
                      + ": "
                      + e.getMessage());
        }
      }
    }

    // Set the NodeInformationProvider that will provide information about the
    // offered services whenever a disco request is received
    try {
      sdm.setNodeInformationProvider(MobilisManager.discoServicesNode, this);
    } catch (Exception e) {
      MobilisManager.getLogger()
          .warning(
              "Problem with NodeInformationProvider: "
                  + MobilisManager.discoServicesNode
                  + " ("
                  + getIdent()
                  + ") "
                  + e.getMessage());
    }

    // try {
    //	String entityID = mJid;
    //	DiscoverItems discoverItems = new DiscoverItems();
    //	Item item = new Item(entityID);
    //	item.setAction(Item.UPDATE_ACTION);
    //	item.setName("Mobilis Agent");
    //	item.setNode(null);
    //	discoverItems.addItem(item);
    //	sdm.publishItems(entityID, discoverItems);
    // } catch (Exception e) {
    //	MobilisManager.getLogger().warning("Problem with ServiceDiscoveryManager: " +
    // e.getMessage());
    // }

    // logging
    MobilisManager.getLogger().info("Mobilis Agent (" + getIdent() + ") started up.");
  }
예제 #30
0
 /**
  * Gets the supported features of the servers pubsub implementation as a standard {@link
  * DiscoverInfo} instance.
  *
  * @return The supported features
  * @throws XMPPException
  */
 public DiscoverInfo getSupportedFeatures() throws XMPPException {
   ServiceDiscoveryManager mgr = ServiceDiscoveryManager.getInstanceFor(con);
   return mgr.discoverInfo(to);
 }