示例#1
0
  /**
   * @see net.sf.kraken.session.TransportSession#sendChatState(org.xmpp.packet.JID,
   *     net.sf.kraken.type.ChatStateType)
   */
  @Override
  public void sendChatState(JID jid, ChatStateType chatState) {
    final Presence presence = conn.getRoster().getPresence(jid.toString());
    if (presence == null || presence.getType().equals(Presence.Type.unavailable)) {
      // don't send chat state to contacts that are offline.
      return;
    }
    Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
    try {
      ChatState state = ChatState.active;
      switch (chatState) {
        case active:
          state = ChatState.active;
          break;
        case composing:
          state = ChatState.composing;
          break;
        case paused:
          state = ChatState.paused;
          break;
        case inactive:
          state = ChatState.inactive;
          break;
        case gone:
          state = ChatState.gone;
          break;
      }

      Message message = new Message();
      message.addExtension(new ChatStateExtension(state));
      chat.sendMessage(message);
    } catch (XMPPException e) {
      // Ignore
    }
  }
示例#2
0
  // TODO: figure out what determines the presence of a RosterEntry's name field
  public void setActiveChatByName(String name) {
    Roster roster = connection.getRoster();

    String activeUser = null;
    if (activeChat != null) {
      activeUser = activeChat.getParticipant();
      int index = activeUser.indexOf("/");
      // Log.d("Jane", "index: " + index);
      if (index >= 0) {
        activeUser = activeUser.substring(0, index);
      }

      if (!chatCache.containsKey(activeUser)) {
        Log.d("Jane", "Caching " + activeUser);
        chatCache.put(activeUser, activeChat);
      }
    }

    for (RosterEntry entry : roster.getEntries()) {
      String potentialName = entry.getName();
      String email = entry.getUser();
      Log.i("Chat", "Checking desired recipient: " + name + " against: " + potentialName);
      if (potentialName != null && potentialName.regionMatches(true, 0, name, 0, name.length())) {
        Log.i("Chat", "Setting active chat to " + potentialName + "/" + email);
        speak("Now talking to " + potentialName);
        if (chatCache.containsKey(email)) {
          activeChat = chatCache.get(email);
        } else {
          Log.d("Chat", "Chat cache did not contain key " + email);
          activeChat = connection.getChatManager().createChat(email, null);
        }
        return;
      } else if (email.contains(name)) { // maybe emails will be ok...
        Log.i("Chat", "Setting active chat to " + email);
        speak("Now talking to " + email);
        if (chatCache.containsKey(email)) {
          activeChat = chatCache.get(email);
        } else {
          activeChat = connection.getChatManager().createChat(email, null);
        }
        return;
      }
    }
    Log.i("Chat", "No friend matches " + name);
    speak("Sorry, but I couldn't find a friend named " + name);
  }
示例#3
0
 /** @see net.sf.kraken.session.TransportSession#sendMessage(org.xmpp.packet.JID, String) */
 @Override
 public void sendMessage(JID jid, String message) {
   Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
   try {
     chat.sendMessage(message);
   } catch (XMPPException e) {
     // Ignore
   }
 }
示例#4
0
  /** @param message 聊天信息 */
  public void chat(String jid, String message) {

    Chat chat = connection.getChatManager().getThreadChat(jid);
    if (chat == null) {
      try {
        connection.getChatManager().createChat(jid, null).sendMessage(message);
      } catch (XMPPException e) {
        e.printStackTrace();
      }
    } else {
      try {
        chat.sendMessage(message);
      } catch (XMPPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
示例#5
0
 /**
  * @see net.sf.kraken.session.TransportSession#sendBuzzNotification(org.xmpp.packet.JID, String)
  */
 @Override
 public void sendBuzzNotification(JID jid, String message) {
   Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
   try {
     Message m = new Message();
     m.setTo(getTransport().convertJIDToID(jid));
     m.addExtension(new BuzzExtension());
     chat.sendMessage(m);
   } catch (XMPPException e) {
     // Ignore
   }
 }
  @Override
  public boolean login() throws RemoteException {
    if (mAdaptee.isAuthenticated()) return true;
    if (!mAdaptee.isConnected()) return false;
    try {

      this.initFeatures(); // pour declarer les features xmpp qu'on
      // supporte

      PacketFilter filter =
          new PacketFilter() {

            @Override
            public boolean accept(Packet packet) {
              if (packet instanceof Presence) {
                Presence pres = (Presence) packet;
                if (pres.getType() == Presence.Type.subscribe) return true;
              }
              return false;
            }
          };

      mAdaptee.addPacketListener(mSubscribePacketListener, filter);

      filter = new PacketTypeFilter(PingExtension.class);
      mAdaptee.addPacketListener(mPingListener, filter);

      mAdaptee.login(mLogin, mPassword, mResource);
      mUserInfo = new UserInfo(mAdaptee.getUser());

      mChatManager = new BeemChatManager(mAdaptee.getChatManager(), mService, mAdaptee.getRoster());
      // nikita: I commented this line because of the logs provided in
      // http://www.beem-project.com/issues/321
      // Also, since the privacylistmanager isn't finished and used, it will be safer to not
      // initialize it
      // mPrivacyListManager = new
      // PrivacyListManagerAdapter(PrivacyListManager.getInstanceFor(mAdaptee));
      mService.initJingle(mAdaptee);
      discoverServerFeatures();

      mRoster = new RosterAdapter(mAdaptee.getRoster(), mService, mAvatarManager);
      mApplication.setConnected(true);
      int mode = mPref.getInt(BeemApplication.STATUS_KEY, 0);
      String status = mPref.getString(BeemApplication.STATUS_TEXT_KEY, "");
      changeStatus(mode, status);
      return true;
    } catch (XMPPException e) {
      Log.e(TAG, "Error while connecting", e);
      mErrorMsg = mService.getString(R.string.error_login_authentication);
      return false;
    }
  }
示例#7
0
 public void startSellingItem() throws XMPPException {
   connection.connect();
   connection.login(String.format(ITEM_ID_AS_LOGIN, itemId), AUCTION_PASSWORD, AUCTION_RESOURCE);
   connection
       .getChatManager()
       .addChatListener(
           new ChatManagerListener() {
             public void chatCreated(Chat chat, boolean createLocally) {
               currentChat = chat;
               chat.addMessageListener(messageListener);
             }
           });
 }
  /**
   * sendMessage
   *
   * @param xmppTo a {@link java.lang.String} object.
   * @param xmppMessage a {@link java.lang.String} object.
   * @return a boolean.
   */
  public boolean sendMessage(String xmppTo, String xmppMessage) {
    if (!isLoggedIn()) {
      connectToServer();
    }
    try {
      ChatManager cm = xmpp.getChatManager();
      cm.createChat(xmppTo, new NullMessageListener()).sendMessage(xmppMessage);
      LOG.debug("XMPP Manager sent message to: {}", xmppTo);
    } catch (XMPPException e) {
      LOG.error("XMPP Exception Sending message ", e);
      return false;
    }

    return true;
  }
示例#9
0
文件: XMPPHelper.java 项目: dhonza/ne
  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;
    }
  }
示例#10
0
文件: Talk.java 项目: neharob/fsnet
  /*
   * (non-Javadoc)
   *
   * @see
   * fr.univartois.ili.fsnet.commons.talk.ITalk#createConversation(java.lang
   * .String)
   */
  @Override
  public Chat createConversation(String pseudoFriend) throws TalkException {
    try {
      Chat chat =
          connection
              .getChatManager()
              .createChat(
                  pseudoFriend,
                  new MessageListener() {
                    @Override
                    public void processMessage(Chat chat, Message message) {}
                  });

      return chat;

    } catch (Exception e) {
      Logger.getAnonymousLogger().log(Level.SEVERE, "", e);
    }
    return null;
  }
示例#11
0
  public void loginCallback(android.os.Message result, XMPPConnection connection) {
    try {
      switch (result.what) {
        case JaneService.LOGIN_FAILED:
          speak("Login failed.");
          break;
        case JaneService.LOGIN_SUCCESSFUL:
          speak("Login successful..");
          break;
      }
      uiMessenger.send(result);
    } catch (RemoteException re) {
      re.printStackTrace();
    }

    this.connection = connection;
    activeChat = null;
    chatServiceListener = new ChatServiceListener(this);

    connection.getChatManager().addChatListener(chatServiceListener);

    localBroadcastManager.registerReceiver(localChatReceiver, new IntentFilter(NEW_MESSAGE));
  }
示例#12
0
  /**
   * 登录
   *
   * @param account 登录帐号
   * @param password 登录密码
   * @return
   */
  public boolean login(String account, String password) {
    try {
      if (connection == null) return false;
      /** 登录 */
      connection.login(account, password, "Spark");
      recvFile();

      ChatManager cm = connection.getChatManager();
      cm.addChatListener(
          new ChatManagerListener() {

            @Override
            public void chatCreated(Chat chat, boolean createdLocally) {
              chat.addMessageListener(
                  new MessageListener() {

                    @Override
                    public void processMessage(Chat chat, Message message) {
                      if (msgListener != null) {
                        msgListener.processMessage(chat, message);
                      } else {
                        if (message.getBody() != null) {
                          Log.d(chat.getParticipant(), message.getBody());
                        }
                      }
                    }
                  });
            }
          });

      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
示例#13
0
  public static void main(String[] args) {
    Scanner inputReader = new Scanner(System.in);
    XMPPConnection connection = null;
    System.out.println("Welcome to the Multi User Chat Desktop Application.");
    boolean notConnected = true;
    while (notConnected) {
      System.out.println("Enter the XMPP server you would like to connect to (e.g. myserver.org):");
      String xmppServer = inputReader.nextLine();
      try {
        System.out.println("Processing... Please wait");
        connection = new XMPPConnection(xmppServer); // connects to server address provided
        connection.connect();
        System.out.println("Connection Successful!\n");
        notConnected = false;
      } catch (Exception e) {
        System.out.println(
            "There was an issue connecting to the XMPP server '"
                + xmppServer
                + "' (We recommend jabber.org)");
      }
    }
    boolean validUserAndPass = false;
    String userName = null;
    while (!validUserAndPass) {
      System.out.println("Please enter your username: "******"Please enter your password: "******"Validating your information...");
        connection.login(userName, password); // attempts to login to the server
        validUserAndPass = true;
        System.out.println("Login Successful!\n");
      } catch (Exception e) {
        System.out.println(
            "Error logging into server - Your username or password may be incorrect");
      }
    }
    Connection connection2 = new XMPPConnection("jabber.org");
    MultiUserChat groupChat2 = null;
    try {
      connection2.connect();
      connection2.login("*****@*****.**", "opencommdesign");
    } catch (XMPPException e1) {
      System.out.println("Hardcoded opencommdesign failed to log in");
    }
    System.out.println("Enter a command to begin (or 'help' to see available commands)");
    MultiUserChat groupChat = null;
    ArrayList<RosterEntry> onlineUsersInRoom =
        new ArrayList<RosterEntry>(); // updated when a user accepts the chat invitation
    boolean chatRoomGenerated =
        false; // checked against to make sure room is not regenerated each time a user is invited
    ChatManager chatmanager = null;
    Chat chat = null;
    boolean programTerminated = false;
    while (!programTerminated) {
      String input = inputReader.nextLine();
      input =
          input
              .trim(); // ignores spaces before and after the command if the command itself is
                       // correct - does not remove spaces mixed into the command
      if (input.startsWith(HELP_VERB) && input.length() == HELP_VERB.length()) {
        System.out.println(COMMAND_OPTIONS); // prints list of available commands
      } else if (input.equals(VIEW_ROOM_VERB)) {
        if (groupChat == null) {
          System.out.println("You are not currently in any chat rooms");
        } else {
          System.out.println("You are currently in the '" + DEFAULT_ROOM_NAME + "' chatroom");
        }
      } else if (input.startsWith(INVITATION_VERB)) {
        String userToInvite =
            input.substring(
                INVITATION_VERB.length()
                    + 1); // +1 accounts for space after verb, isolates the username

        try {
          if (!chatRoomGenerated) {
            System.out.println("Initializing a default chat room...");
            groupChat = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org");
            groupChat.create(
                DEFAULT_ROOM_NAME); // initializes a default instant room, automatically placing the
                                    // user in it
            groupChat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
            System.out.println("Default chat room initialized!");
            // listen for invitation rejections
            groupChat.addInvitationRejectionListener(
                new InvitationRejectionListener() {
                  public void invitationDeclined(String invitee, String reason) {
                    System.out.println("User '" + invitee + "' declined your chat invitation.");
                    System.out.println("Reason: " + reason);
                  }
                });
            groupChat2 =
                new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org");
            groupChat2.join(DEFAULT_ROOM_NAME); // hardcoded second user joins the room
            chatRoomGenerated = true;
            chatmanager = connection.getChatManager();
            chat =
                chatmanager.createChat(
                    userToInvite,
                    new MessageListener() {
                      public void processMessage(Chat chat, Message message) {
                        System.out.println("Received message: " + message);
                      }
                    });
          }
          groupChat.invite(
              userToInvite, "User '" + userName + "' has invited you to join a chat room");

        } catch (XMPPException e) {
          System.out.println("Error occured in creating the chat room");
        }
      } else if (input.equals(VIEW_BUDDY_VERB)) { // if user enters viewBuddyList
        Roster roster = connection.getRoster(); // gets other users on this connection
        Collection<RosterEntry> entries = roster.getEntries();
        ArrayList<RosterEntry> onlineUsers = new ArrayList<RosterEntry>();
        ArrayList<RosterEntry> offlineUsers = new ArrayList<RosterEntry>();
        for (RosterEntry entry : entries) {
          if (entry
              .toString()
              .contains(
                  "[Buddies]")) { // if other users are marked as buddies, print them to the list
            String user = entry.getUser();
            if (roster.getPresence(user) == null) { // if user is offline, add them to offlineUsers
              offlineUsers.add(entry);
            } else {
              onlineUsers.add(entry);
            }
          }
        }

        System.out.println("Online Buddies in your chat room:");
        if (groupChat.getOccupantsCount() == 1) {
          System.out.println("There are 0 buddies in your chat room");
        } else {
          @SuppressWarnings("unchecked")
          Collection<String> users = (Collection<String>) groupChat.getOccupants();
          for (@SuppressWarnings("unused") String user : users) {
            System.out.println(user);
          }
        }
        System.out.println("Online Buddies:");
        if (onlineUsers.size() == 0) {
          System.out.println("There are 0 buddies online");
        } else {
          for (RosterEntry entry : onlineUsers) {
            String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]"));
            System.out.println(user);
          }
        }
        System.out.println("Offline Buddies:");
        if (offlineUsers.size() == 0) {
          System.out.println("There are 0 buddies offline");
        } else {
          for (RosterEntry entry : offlineUsers) {
            String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]"));
            System.out.println(user);
          }
        }
        System.out.println("");
      } else {
        System.out.println(
            "Command not recognized.  Type 'help' to see a list of available commands");
      }

      if (!programTerminated) {
        System.out.println("Enter a command: ");
      }
    }
  }
示例#14
0
  public void connect() {

    try {
      ConnectionConfiguration xmppConfig =
          new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
      connection = new XMPPConnection(xmppConfig);

      connection.connect();

      SASLAuthentication.supportSASLMechanism("PLAIN", 0);
      // Get data
      String user = Controller.getSettings().USERNAME;
      String password = Controller.getSettings().PASSWORD;
      connection.login(user, password);
      chatManager = connection.getChatManager();
      for (Object name : Controller.getSettings().ADMIN_LIST.keySet().toArray()) {

        createAndAddToChat(name.toString());
        chat(name.toString())
            .sendMessage(
                Controller.getName()
                    + " has activated on server : "
                    + Controller.getPluginInstance().getServer().getServerName());
      }

      for (Object name : Controller.getSettings().USER_LIST.keySet().toArray()) {
        createAndAddToChat(name.toString());
        chat(name.toString())
            .sendMessage(
                Controller.getName()
                    + " has activated on server : "
                    + Controller.getPluginInstance().getServer().getServerName());
      }
      chatManager.addChatListener(
          new ChatManagerListener() {

            public void chatCreated(Chat chat, boolean createdLocally) {
              if (!createdLocally && !chatExactlyExists(chat)) {
                if (Controller.getSettings().OPEN_CHANNEL) {
                  try {
                    chat.sendMessage("You have now been added to this server's chat room.");
                  } catch (XMPPException ex) {
                    Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  createAndAddToChat(chat);

                } else {

                  if (Controller.getSettings().isUser(correctAdress(chat.getParticipant()))) {
                    try {
                      chat.sendMessage("You have now been added to this server's chat room.");
                    } catch (XMPPException ex) {
                      Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    createAndAddToChat(chat);

                  } else {
                    try {
                      chat.sendMessage(
                          "You do not have permission to join this server's chat. Please contact an admin.");
                    } catch (XMPPException ex) {
                      Logger.getLogger(XMPPManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                  }
                }
              }
            }
          });

    } catch (XMPPException ex) {
      System.out.println("Failure to connect : " + ex.getMessage());
    }
  }
  private synchronized void setUp() {

    try {

      if (config != null) {
        if (config.getServletConfig().getInitParameter(XMPP_AUTH) != null) {
          authToken = config.getServletConfig().getInitParameter(XMPP_AUTH);
        } else {
          throw new IllegalStateException(
              "No authorization token specified. Please make sure your web.xml contains:"
                  + "\n        <init-param>\n"
                  + "            <param-name>org.atmosphere.plugin.xmpp.XMPPBroadcaster.authorization</param-name>\n"
                  + "            <param-value>principal:password</param-value>\n"
                  + "        </init-param>");
        }

        if (config.getServletConfig().getInitParameter(XMPP_SERVER) != null) {
          uri = URI.create(config.getServletConfig().getInitParameter(XMPP_SERVER));
        } else if (uri == null) {
          throw new NullPointerException("uri cannot be null");
        }

        if (config.getServletConfig().getInitParameter(XMPP_DEBUG) != null) {
          XMPPConnection.DEBUG_ENABLED = true;
        }
      }

      ConnectionConfiguration config = null;
      int port = -1;
      try {
        port = uri.getPort();
      } catch (Throwable t) {;
      }
      if (port == -1) {
        config = new ConnectionConfiguration(uri.getHost());
      } else {
        config = new ConnectionConfiguration(uri.getHost(), port);
      }

      xmppConnection = new XMPPConnection(config);
      xmppConnection.connect();
      SASLAuthentication.supportSASLMechanism("PLAIN", 0);
      String[] credentials = authToken.split(":");

      xmppConnection.login(credentials[0], credentials[1], getID());

      logger.info("Subscribing to: " + getID());
      channel =
          xmppConnection
              .getChatManager()
              .createChat(
                  getID(),
                  new MessageListener() {

                    public void processMessage(Chat chat, Message message) {
                      broadcastReceivedMessage(message.getBody());
                    }
                  });

      logger.info("Connected to: " + getID());
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
示例#16
0
 void initiateMessageListener() {
   chatManager = connection.getChatManager();
   messageListener = new SmackMessageListener();
 }
示例#17
0
 public XMPPAuction(XMPPConnection connection, String itemId) {
   AuctionMessageTranslator translator = translatorFor(connection);
   chat = connection.getChatManager().createChat(auctionId(itemId, connection), translator);
   addAuctionEventListener(chatDisconnectorFor(translator));
 }
示例#18
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;
    }
  }
示例#19
0
 private ShadowChatManager getShadowChatManager() {
   return Robolectric.shadowOf_(xmppConnection.getChatManager());
 }