Пример #1
0
 /**
  * Closes the current connection and restarts Spark.
  *
  * @param reason the reason for logging out. This can be if user gave no reason.
  */
 public void closeConnectionAndInvoke(String reason) {
   final XMPPConnection con = SparkManager.getConnection();
   if (con.isConnected()) {
     if (reason != null) {
       Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
       con.disconnect(byePresence);
     } else {
       con.disconnect();
     }
   }
   if (!restartApplicationWithScript()) {
     restartApplicationWithJava();
   }
 }
 private void xmppTalk() {
   System.err.println("INFO: KML-Simulating has started.");
   System.err.println("INFO: Stage 1: Initializing XMPP connection.");
   XMPPConnection connection = this.xmppInitialize();
   if (connection == null) return;
   System.err.println("INFO: Stage 2: Reading and posting roster.");
   this.xmppRosterPost(connection);
   System.err.println("INFO: Stage 3: Walking through coordinates.");
   int interval = 1000;
   try {
     interval = Integer.parseInt(this.interval);
   } catch (NumberFormatException e) {
   }
   for (Coordinate c : this.coordinates) {
     this.xmppLocationUpdate(connection, c.lat, c.lon);
     System.err.println("INFO: Waiting for " + interval + "ms.");
     try {
       LocationJabberer.sleep(interval);
     } catch (InterruptedException e) {
     }
   }
   System.err.println("INFO: Stage 4: Done walking. Shutting down connection.");
   connection.disconnect();
   System.err.println("INFO: Connection closed.");
 }
 /** @param error null if connection is closed by user */
 void logoutImpl(Exception error) {
   synchronized (this) {
     if (isLoggedIn()) {
       loggedIn.set(false);
       LOG.infof(
           "disconnecting from {0} at {1}:{2} ...",
           connection.getServiceName(), connection.getHost(), connection.getPort());
       connection.disconnect();
       synchronized (friends) {
         friends.clear();
       }
       XMPPConnection.removeConnectionCreationListener(smackConnectionListener);
       connection = null;
       LOG.info("disconnected.");
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(
               XMPPFriendConnectionImpl.this, FriendConnectionEvent.Type.DISCONNECTED, error));
       ChatStateManager.remove(connection);
       if (discoInfoListener != null) {
         discoInfoListener.cleanup();
       }
       if (noSaveFeatureInitializer != null) {
         noSaveFeatureInitializer.cleanup();
       }
       if (idleStatusMonitor != null) {
         idleStatusMonitor.stop();
       }
       if (xmppActivityListener != null) {
         xmppActivitySupport.removeListener(xmppActivityListener);
       }
       featureRegistry.deregisterInitializer(NoSaveFeature.ID);
     }
   }
 }
Пример #4
0
  /*
   * (non-Javadoc)
   *
   * @see
   * fr.univartois.ili.fsnet.commons.talk.ITalk#createAccount(java.lang.String
   * , java.lang.String, java.util.Map)
   */
  @Override
  public boolean createAccount(String userName, String password, Map<String, String> map) {
    {
      if (!connection.isConnected()) {
        try {
          connection.connect();
        } catch (XMPPException e3) {

          Logger.getAnonymousLogger().log(Level.SEVERE, "", e3);
        }
      }

      try {
        Map<String, String> finalMap = map;
        if (finalMap == null) {
          finalMap = new HashMap<String, String>();
        }
        accountManager.createAccount(userName, password, finalMap);

        connection.disconnect();
        // Thread.sleep(6000);
        connection.connect();
        connection.login(userName, password);

        return true;
      } catch (XMPPException e2) {
        Logger.getAnonymousLogger().log(Level.SEVERE, "", e2);
      }
      return false;
    }
  }
Пример #5
0
 @After
 public void tearDown() {
   xmppService = null;
   xmppConnection.disconnect();
   xmppConnection = null;
   xmppConnectionProvider = null;
 }
 /** {@inheritDoc} */
 @Override
 public void destroy() {
   super.destroy();
   synchronized (xmppConnection) {
     if (xmppConnection != null) {
       xmppConnection.disconnect();
     }
   }
 }
 /** Disconnects from chatserver and releases all resources. */
 public void disconnect() {
   connection.getRoster().removeRosterListener(leagueRosterListener);
   try {
     connection.disconnect();
   } catch (final NotConnectedException e) {
     e.printStackTrace();
   }
   stop = true;
 }
Пример #8
0
  public void broadcast() throws XMPPException {

    Message newmsg = new Message();
    newmsg.setTo("*****@*****.**");
    newmsg.setSubject("重要通知");
    newmsg.setBody("今天下午2点60分有会!");
    newmsg.setType(Message.Type.headline); // normal支持离线
    connection.sendPacket(newmsg);
    connection.disconnect();
  }
 /**
  * Unwind upon login error - broadcast login failed, remove conn creation listener from smack, set
  * conn to null, disconnect if need be, etc
  *
  * @param e Exception which occurred during login
  */
 private synchronized void handleLoginError(Exception e) {
   loggingIn.set(false);
   connectionMulticaster.broadcast(
       new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECT_FAILED, e));
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
   org.jivesoftware.smack.XMPPConnection.removeConnectionCreationListener(smackConnectionListener);
   connection = null;
 }
Пример #10
0
  public void close() throws XMPPException {
    for (Object name : Controller.getSettings().ADMIN_LIST.keySet().toArray()) {
      chat(name.toString())
          .sendMessage(Controller.getName() + " remote console is now closing down.");
    }

    for (Object name : Controller.getSettings().USER_LIST.keySet().toArray()) {
      chat(name.toString()).sendMessage(Controller.getName() + " remote chat is now closing down.");
    }

    connection.disconnect();
  }
Пример #11
0
  public void getOfflineBroadcast() throws XMPPException {
    OfflineMessageManager offlineManager = new OfflineMessageManager(connection);
    try {
      Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager.getMessages();

      System.out.println(offlineManager.supportsFlexibleRetrieval());
      System.out.println("离线消息数量: " + offlineManager.getMessageCount());

      Map<String, ArrayList<Message>> offlineMsgs = new HashMap<String, ArrayList<Message>>();

      while (it.hasNext()) {
        org.jivesoftware.smack.packet.Message message = it.next();
        System.out.println(
            "收到离线消息, Received from 【" + message.getFrom() + "】 message: " + message.getBody());
        String fromUser = message.getFrom().split("/")[0];

        if (offlineMsgs.containsKey(fromUser)) {
          offlineMsgs.get(fromUser).add(message);
        } else {
          ArrayList<Message> temp = new ArrayList<Message>();
          temp.add(message);
          offlineMsgs.put(fromUser, temp);
        }
      }

      // 在这里进行处理离线消息集合......
      Set<String> keys = offlineMsgs.keySet();
      Iterator<String> offIt = keys.iterator();
      while (offIt.hasNext()) {
        String key = offIt.next();
        ArrayList<Message> ms = offlineMsgs.get(key);

        for (int i = 0; i < ms.size(); i++) {
          System.out.println("-->" + ms.get(i));
        }
      }

      offlineManager.deleteMessages();
    } catch (Exception e) {
      e.printStackTrace();
    }
    offlineManager.deleteMessages(); // 删除所有离线消息
    Presence presence = new Presence(Presence.Type.available);
    connection.sendPacket(presence); // 上线了
    connection.disconnect(); // 关闭连接
  }
Пример #12
0
  public static void sendViaXMPP(String message) {
    String userHome = System.getProperty("user.home");
    try {
      String jabberConfig = FileUtils.readFileToString(new File(userHome + "/.nexmpp"));
      String[] xmppParams = jabberConfig.split(" ");
      if (xmppParams.length != 4) {
        System.err.println(
            "Wrong .nexmpp format, should be: server server_login server_password jabber_id");
        return;
      }
      String server = xmppParams[0];
      String serverLogin = xmppParams[1];
      String serverPassword = xmppParams[2];
      String jabberId = xmppParams[3].split("\n")[0];

      Calendar cal = Calendar.getInstance();
      int hour24 = cal.get(Calendar.HOUR_OF_DAY);
      if (hour24 <= 9) { // do not wake me up :)
        return;
      }
      try {
        String hostName = InetAddress.getLocalHost().getHostName();
        //                if (hostName.endsWith(".local") || hostName.startsWith("eduroam") ||
        // hostName.startsWith("dhcp")) {
        //                    return;
        //                }
        message = hostName + ": " + message;

        XMPPConnection connection = new XMPPConnection(server);
        connection.connect();
        connection.login(serverLogin, serverPassword);
        ChatManager chatmanager = connection.getChatManager();
        Chat chat = chatmanager.createChat(jabberId, null);
        chat.sendMessage(message);
        connection.disconnect();
      } catch (XMPPException e) {
        e.printStackTrace();
      } catch (UnknownHostException e) {
        e.printStackTrace();
      }

    } catch (IOException e) {
      System.err.println("No " + userHome + "/.nexmpp file.");
      return;
    }
  }
Пример #13
0
  public void cleanupConnection() {
    if (con != null) {
      con.removePacketListener(messagePacketListener);
      con.removePacketListener(presencePacketListener);

      if (connectionListener != null) {
        con.removeConnectionListener(connectionListener);
      }
    }

    if (isConnected()) {
      try {
        con.disconnect();
      } catch (NotConnectedException e) {
      }
    }
  }
Пример #14
0
  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   */
  public void shutdown() {
    final XMPPConnection con = SparkManager.getConnection();

    if (con.isConnected()) {
      // Send disconnect.
      con.disconnect();
    }

    // Notify all MainWindowListeners
    try {
      fireWindowShutdown();
    } catch (Exception ex) {
      Log.error(ex);
    }
    // Close application.
    if (!Default.getBoolean("DISABLE_EXIT")) System.exit(1);
  }
Пример #15
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.");
  }
Пример #16
0
 @Override
 public void run() {
   if (xmppManager.isConnected() && !xmppManager.isRunning()) {
     Log.d(LOG_TAG, "terminatePersistentConnection()... run()");
     XMPPConnection connection = xmppManager.getConnection();
     try {
       xmppManager.setRunning(true);
       connection.disconnect();
       connection.removePacketListener(xmppManager.getNotificationPacketListener());
       connection.removeConnectionListener(xmppManager.getConnectionListener());
       callback.onSuccess();
     } catch (Exception e) {
       Log.e(LOG_TAG, "XMPP disconnection failed", e);
       callback.onFailed("XMPP disconnection failed");
     } finally {
       xmppManager.setRunning(false);
     }
   } else {
     Log.w(LOG_TAG, "XMPP is not connected or is running");
     callback.onFailed("XMPP is not connected or is running");
   }
 }
Пример #17
0
 public void stop() {
   connection.disconnect();
 }
Пример #18
0
  public String getJid() {
    try {
      System.out.println("getJid method executed");
      ConnectionConfiguration config = new ConnectionConfiguration(DOMAIN, PORT);
      config.setSASLAuthenticationEnabled(true);
      XMPPConnection con = new XMPPConnection(config);
      con.connect();
      System.out.println("Connection ok");
      con.login("searchuser", "search");
      System.out.println("Logged in");
      UserSearchManager search = new UserSearchManager(con);
      System.out.println("User Search created");
      Collection services = search.getSearchServices();
      System.out.println("Search Services found:");
      Iterator it = services.iterator();
      while (it.hasNext()) {
        System.out.println(it.next());
      }
      Form searchForm = search.getSearchForm("search." + "cuopencomm");
      System.out.println("Available search fields:");
      Iterator<FormField> fields = searchForm.getFields();
      while (fields.hasNext()) {
        FormField field = fields.next();
        System.out.println(field.getVariable() + " : " + field.getType());
      }

      Form answerForm = searchForm.createAnswerForm();
      answerForm.setAnswer("search", email);
      answerForm.setAnswer("Email", true);

      ReportedData data = search.getSearchResults(answerForm, "search." + "cuopencomm");

      System.out.println("\nColumns that are included as part of the search results:");
      Iterator<Column> columns = data.getColumns();
      while (columns.hasNext()) {
        System.out.println(columns.next().getVariable());
      }

      System.out.println("\nThe jids and emails from our each of our hits:");
      Iterator<Row> rows = data.getRows();
      while (rows.hasNext()) {
        Row row = rows.next();

        Iterator<String> jids = row.getValues("jid");
        Iterator<String> emails = row.getValues("email");
        String jidFound = null;
        String emailFound = null;

        while (emails.hasNext() && jids.hasNext()) {
          jidFound = jids.next();
          emailFound = emails.next();
          System.out.println(jidFound);
          System.out.println(emailFound);
          if (emailFound.equalsIgnoreCase(email)) {
            jid = jidFound;
            String[] jidCleaned = jid.split("@");
            jid = jidCleaned[0];
            System.out.println(jid);
          }
        }
      }
      con.disconnect();
      return jid;
    } catch (Exception ex) {
      System.out.println("Caught Exception :" + ex.getMessage());
      return jid;
    }
  }
Пример #19
0
 @Override
 public void reconnectionFailed(Exception e) {
   LOG.warn("XMPP reconnection failed", e);
   xmpp.disconnect();
   instance = null;
 }
Пример #20
0
 public void destroy() {
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
 }
 /** {@inheritDoc} */
 @Override
 public boolean disconnect() {
   if (mAdaptee != null && mAdaptee.isConnected()) mAdaptee.disconnect();
   return true;
 }
Пример #22
0
 /** 关闭XMPP连接 */
 public boolean disconnect() throws RemoteException {
   if (connection != null && connection.isConnected()) {
     connection.disconnect();
   }
   return true;
 }
Пример #23
0
 public void closeConnection() {
   mXMPPConnection.disconnect();
 }
Пример #24
0
 public void disconnect() {
   if (mConnection != null) {
     mConnection.disconnect();
   }
 }
Пример #25
0
  /** @see net.sf.kraken.session.TransportSession#cleanUp() */
  @Override
  public void cleanUp() {
    if (timer != null) {
      try {
        timer.cancel();
      } catch (Exception e) {
        // Ignore
      }
      timer = null;
    }
    if (mailCheck != null) {
      try {
        mailCheck.cancel();
      } catch (Exception e) {
        // Ignore
      }
      mailCheck = null;
    }
    if (conn != null) {
      try {
        conn.removeConnectionListener(listener);
      } catch (Exception e) {
        // Ignore
      }

      try {
        conn.removePacketListener(listener);
      } catch (Exception e) {
        // Ignore
      }
      try {
        conn.removePacketListener(presenceHandler);
      } catch (Exception e) {
        // Ignore
      }
      try {
        conn.getChatManager().removeChatListener(listener);
      } catch (Exception e) {
        // Ignore
      }
      try {
        conn.getRoster().removeRosterListener(listener);
      } catch (Exception e) {
        // Ignore
      }
      try {
        conn.disconnect();
      } catch (Exception e) {
        // Ignore
      }
    }
    conn = null;
    listener = null;
    presenceHandler = null;
    if (runThread != null) {
      try {
        runThread.interrupt();
      } catch (Exception e) {
        // Ignore
      }
      runThread = null;
    }
  }
Пример #26
0
 /*
  * (non-Javadoc)
  *
  * @see fr.univartois.ili.fsnet.commons.talk.ITalk#stop()
  */
 @Override
 public void stop() throws TalkException {
   connection.disconnect();
 }