コード例 #1
0
ファイル: MainWindow.java プロジェクト: dentalht/AppChat
  public boolean restartApplicationWithScript() {
    String command = null;
    try {
      if (Spark.isWindows()) {
        String sparkExe =
            getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME) + ".exe";
        if (!new File(sparkExe).exists()) {
          Log.warning("Client EXE file does not exist");
          return false;
        }
        String starterExe = getCommandPath() + File.separator + "starter.exe";
        if (!new File(starterExe).exists()) {
          Log.warning("Starter EXE file does not exist");
          return false;
        }
        command = starterExe + " \"" + sparkExe + "\"";
      } else if (Spark.isLinux()) {
        command = getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME);
        if (!new File(command).exists()) {
          Log.warning("Client startup script does not exist");
          return false;
        }
      } else if (Spark.isMac()) {
        command = "open -a " + Default.getString(Default.SHORT_NAME);
      }

      Runtime.getRuntime().exec(command);
      System.exit(0);
      return true;
    } catch (IOException e) {
      Log.error("Error trying to restart application with script", e);
      return false;
    }
  }
コード例 #2
0
ファイル: TranslatorUtil.java プロジェクト: BlueBody/Spark
  private static String useGoogleTranslator(String text, TranslationType type) {

    String response = "";
    String urlString =
        "http://translate.google.com/translate_t?text=" + text + "&langpair=" + type.getID();
    // disable scripting to avoid requiring js.jar
    HttpUnitOptions.setScriptingEnabled(false);

    // create the conversation object which will maintain state for us
    WebConversation wc = new WebConversation();

    // Obtain the google translation page
    WebRequest webRequest = new GetMethodWebRequest(urlString);
    // required to prevent a 403 forbidden error from google
    webRequest.setHeaderField("User-agent", "Mozilla/4.0");

    try {
      WebResponse webResponse = wc.getResponse(webRequest);
      // NodeList list = webResponse.getDOM().getDocumentElement().getElementsByTagName("div");
      try {
        NodeList list2 =
            XPathAPI.selectNodeList(webResponse.getDOM(), "//span[@id='result_box']/span/text()");

        for (int i = 0; i < list2.getLength(); ++i) {
          response = response + list2.item(i).getNodeValue() + " ";
        }

      } catch (TransformerException e) {
        Log.warning("Translator error", e);
      }

      //            int length = list.getLength();
      //            for (int i = 0; i < length; i++) {
      //                Element element = (Element)list.item(i);
      //                if ("result_box".equals(element.getAttribute("id"))) {
      //                    Node translation = element.getFirstChild();
      //                    if (translation != null) {
      //                        response = translation.getNodeValue();
      //                    }
      //                }
      //            }
    } catch (MalformedURLException e) {
      Log.error("Could not for url: " + e);
    } catch (IOException e) {
      Log.error("Could not get response: " + e);
    } catch (SAXException e) {
      Log.error("Could not parse response content: " + e);
    }

    return response;
  }
コード例 #3
0
ファイル: MainWindow.java プロジェクト: dentalht/AppChat
 private File getLibDirectory() throws IOException {
   File jarFile;
   try {
     jarFile = new File(Startup.class.getProtectionDomain().getCodeSource().getLocation().toURI());
   } catch (Exception e) {
     Log.error("Cannot get jar file containing the startup class", e);
     return null;
   }
   if (!jarFile.getName().endsWith(".jar")) {
     Log.error("The startup class is not packaged in a jar file");
     return null;
   }
   File libDir = jarFile.getParentFile();
   return libDir;
 }
コード例 #4
0
ファイル: MainWindow.java プロジェクト: dentalht/AppChat
  /**
   * Checks for the latest update on the server.
   *
   * @param forced true if you want to bypass the normal checking security.
   */
  private void checkForUpdates(final boolean forced) {
    final CheckUpdates updater = new CheckUpdates();
    try {
      final SwingWorker updateThread =
          new SwingWorker() {
            public Object construct() {
              try {
                Thread.sleep(50);
              } catch (InterruptedException e) {
                Log.error(e);
              }
              return "ok";
            }

            public void finished() {
              try {
                updater.checkForUpdate(forced);
              } catch (Exception e) {
                Log.error("There was an error while checking for a new update.", e);
              }
            }
          };

      updateThread.start();

    } catch (Exception e) {
      Log.warning("Error updating.", e);
    }
  }
コード例 #5
0
ファイル: Notes.java プロジェクト: justin0127/IM
  private void saveNotes() {
    String note = textPane.getText();

    // Check for empty note.
    if (!ModelUtil.hasLength(note)) {
      return;
    }

    // Save note.
    AgentSession agentSession = FastpathPlugin.getAgentSession();
    try {
      agentSession.setNote(sessionID, note);
      saveButton.setEnabled(false);
      statusLabel.setText(" " + FpRes.getString("message.notes.updated"));
      SwingWorker worker =
          new SwingWorker() {
            public Object construct() {
              try {
                Thread.sleep(3000);
              } catch (InterruptedException e1) {
                Log.error(e1);
              }
              return true;
            }

            public void finished() {
              statusLabel.setText("");
            }
          };
      worker.start();
    } catch (XMPPException e1) {
      showError(FpRes.getString("message.unable.to.update.notes"));
      Log.error("Could not commit note.", e1);
    }
  }
コード例 #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
  public void removePrivacyList(String listName) {
    try {
      privacyManager.deletePrivacyList(listName);

      _privacyLists.remove(getPrivacyList(listName));
    } catch (XMPPException e) {
      Log.warning("Could not remove PrivacyList " + listName);
      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: ChatRoomImpl.java プロジェクト: kadet108/blucargo
  /**
   * Sends a message to the appropriate jid. The message is automatically added to the transcript.
   *
   * @param message the message to send.
   */
  public void sendMessage(Message message) {
    lastActivity = System.currentTimeMillis();

    try {
      getTranscriptWindow()
          .insertMessage(getNickname(), message, ChatManager.TO_COLOR, Color.white);
      getChatInputEditor().selectAll();

      getTranscriptWindow().validate();
      getTranscriptWindow().repaint();
      getChatInputEditor().clear();
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }

    // Before sending message, let's add our full jid for full verification
    message.setType(Message.Type.chat);
    message.setTo(participantJID);
    message.setFrom(SparkManager.getSessionManager().getJID());

    // Notify users that message has been sent
    fireMessageSent(message);

    addToTranscript(message, false);

    getChatInputEditor().setCaretPosition(0);
    getChatInputEditor().requestFocusInWindow();
    scrollToBottom();

    // No need to request displayed or delivered as we aren't doing anything
    // with this
    // information.
    MessageEventManager.addNotificationsRequests(message, true, false, false, true);

    // Send the message that contains the notifications request
    try {
      fireOutgoingMessageSending(message);
      SparkManager.getConnection().sendPacket(message);
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }
  }
コード例 #9
0
  /** Creating PrivacyListManager instance */
  private PrivacyManager() {
    XMPPConnection conn = SparkManager.getConnection();
    if (conn == null) {
      Log.error("Privacy plugin: Connection not initialized.");
    }

    _active = checkIfPrivacyIsSupported(conn);

    if (_active) {
      privacyManager = PrivacyListManager.getInstanceFor(conn);
      initializePrivacyLists();
    }
  }
コード例 #10
0
  public void setListAsDefault(String listname) {

    try {
      privacyManager.setDefaultListName(listname);
      fireListSetAsDefault(listname);
      getPrivacyList(listname).setListIsDefault(true);
      for (SparkPrivacyList plist : _privacyLists) {
        if (!plist.getListName().equals(listname)) plist.setListIsDefault(false);
      }
    } catch (XMPPException e) {
      Log.warning("Could not set PrivacyList " + listname + " as default");
      e.printStackTrace();
    }
  }
コード例 #11
0
  public RoarPreference() {

    _props = RoarProperties.getInstance();

    try {
      if (EventQueue.isDispatchThread()) {
        _prefPanel = new RoarPreferencePanel();
      } else {
        EventQueue.invokeAndWait(() -> _prefPanel = new RoarPreferencePanel());
      }
    } catch (Exception e) {
      Log.error(e);
    }
  }
コード例 #12
0
ファイル: MainWindow.java プロジェクト: dentalht/AppChat
 public boolean restartApplicationWithJava() {
   String javaBin =
       System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java";
   try {
     String toExec[] =
         new String[] {javaBin, "-cp", getClasspath(), "org.jivesoftware.launcher.Startup"};
     Runtime.getRuntime().exec(toExec);
   } catch (Exception e) {
     Log.error("Error trying to restart application with java", e);
     return false;
   }
   System.exit(0);
   return true;
 }
コード例 #13
0
 public void declineDefaultList() {
   try {
     if (hasDefaultList()) {
       privacyManager.declineDefaultList();
       fireListRemovedAsDefault(getDefaultList().getListName());
       for (SparkPrivacyList plist : _privacyLists) {
         plist.setListIsDefault(false);
       }
     }
   } catch (XMPPException e) {
     Log.warning("Could not decline default privacy list");
     e.printStackTrace();
   }
 }
コード例 #14
0
  public void declineActiveList() {
    try {

      if (hasActiveList()) {
        privacyManager.declineActiveList();
        fireListDeActivated(getActiveList().getListName());
        _presenceHandler.removeIconsForList(getActiveList());
      }
      for (SparkPrivacyList plist : _privacyLists) {
        plist.setListAsActive(false);
      }
    } catch (XMPPException e) {
      Log.warning("Could not decline active privacy list");
      e.printStackTrace();
    }
  }
コード例 #15
0
ファイル: ContactItem.java プロジェクト: enson16855/Spark
 /** Update avatar icon. */
 public void updateAvatarInSideIcon() {
   try {
     final URL url = getAvatarURL();
     if (url != null) {
       if (!avatarsShowing) {
         setSideIcon(null);
       } else {
         ImageIcon icon = new ImageIcon(url);
         icon = GraphicUtils.scale(icon, iconSize, iconSize);
         setSideIcon(icon);
       }
     }
   } catch (MalformedURLException e) {
     Log.error(e);
   }
 }
コード例 #16
0
ファイル: MainWindow.java プロジェクト: dentalht/AppChat
  /**
   * 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);
  }
コード例 #17
0
  public SparkPrivacyList createPrivacyList(String listName) {
    PrivacyItem item = new PrivacyItem(null, true, 999999);
    ArrayList<PrivacyItem> items = new ArrayList<PrivacyItem>();
    items.add(item);
    SparkPrivacyList sparklist = null;
    try {
      privacyManager.createPrivacyList(listName, items);
      privacyManager.getPrivacyList(listName).getItems().remove(item);
      sparklist = new SparkPrivacyList(privacyManager.getPrivacyList(listName));
      _privacyLists.add(sparklist);
      sparklist.addSparkPrivacyListener(_presenceHandler);
    } catch (XMPPException e) {
      Log.warning("Could not create PrivacyList " + listName);
      e.printStackTrace();
    }

    return sparklist;
  }
コード例 #18
0
  private void initializePrivacyLists() {
    try {
      PrivacyList[] lists = privacyManager.getPrivacyLists();

      for (PrivacyList list : lists) {
        SparkPrivacyList sparkList = new SparkPrivacyList(list);
        sparkList.addSparkPrivacyListener(_presenceHandler);
        _privacyLists.add(sparkList);
      }
    } catch (XMPPException e) {
      Log.error("Could not load PrivacyLists");
      e.printStackTrace();
    }

    if (hasDefaultList()) {
      setListAsActive(getDefaultList().getListName());
    }
  }
コード例 #19
0
  public void setListAsActive(String listname) {
    try {
      privacyManager.setActiveListName(listname);
      fireListActivated(listname);
      if (hasActiveList()) {
        _presenceHandler.removeIconsForList(getActiveList());
      }
      getPrivacyList(listname).setListAsActive(true);
      for (SparkPrivacyList plist : _privacyLists) {
        if (!plist.getListName().equals(listname)) plist.setListAsActive(false);
      }
      _presenceHandler.setIconsForList(getActiveList());

    } catch (XMPPException e) {
      Log.warning("Could not activate PrivacyList " + listname);
      e.printStackTrace();
    }
  }
コード例 #20
0
  private void handleVCardInformation(VCard vcard, String phoneNumber) {
    if (vcard.getError() != null) {
      return;
    }

    String firstName = vcard.getFirstName();
    String lastName = vcard.getLastName();
    if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) {
      titleLabel.setText(firstName + " " + lastName);
    } else if (ModelUtil.hasLength(firstName)) {
      titleLabel.setText(firstName);
    }

    phoneLabel.setText(phoneNumber);

    String jobTitle = vcard.getField("TITLE");
    if (jobTitle != null) {
      professionLabel.setText(jobTitle);
    }

    byte[] avatarBytes = null;
    try {
      avatarBytes = vcard.getAvatar();
    } catch (Exception e) {
      Log.error("Cannot retrieve avatar bytes.", e);
    }

    if (avatarBytes != null) {
      try {
        ImageIcon avatarIcon = new ImageIcon(avatarBytes);
        avatarLabel.setIcon(avatarIcon);
        avatarLabel.invalidate();
        avatarLabel.validate();
        avatarLabel.repaint();
      } catch (Exception e) {
        // no issue
      }
    }

    invalidate();
    validate();
    repaint();
  }
コード例 #21
0
ファイル: ChatRoomImpl.java プロジェクト: kadet108/blucargo
  /**
   * The current SendField has been updated somehow.
   *
   * @param e - the DocumentEvent to respond to.
   */
  public void insertUpdate(DocumentEvent e) {
    checkForText(e);

    if (!sendTypingNotification) {
      return;
    }
    lastTypedCharTime = System.currentTimeMillis();

    // If the user pauses for more than two seconds, send out a new notice.
    if (sendNotification) {
      try {
        SparkManager.getMessageEventManager()
            .sendComposingNotification(getParticipantJID(), threadID);
        sendNotification = false;
      } catch (Exception exception) {
        Log.error("Error updating", exception);
      }
    }
  }
コード例 #22
0
ファイル: VCardEditor.java プロジェクト: kadet108/blucargo
  /** Saves the VCard. */
  private void saveVCard() {
    final VCard vcard = new VCard();

    // Save personal info
    vcard.setFirstName(personalPanel.getFirstName());
    vcard.setLastName(personalPanel.getLastName());
    vcard.setMiddleName(personalPanel.getMiddleName());
    vcard.setEmailHome(personalPanel.getEmailAddress());
    vcard.setNickName(personalPanel.getNickname());

    // Save business info
    vcard.setOrganization(businessPanel.getCompany());
    vcard.setAddressFieldWork("STREET", businessPanel.getStreetAddress());
    vcard.setAddressFieldWork("LOCALITY", businessPanel.getCity());
    vcard.setAddressFieldWork("REGION", businessPanel.getState());
    vcard.setAddressFieldWork("PCODE", businessPanel.getZipCode());
    vcard.setAddressFieldWork("CTRY", businessPanel.getCountry());
    vcard.setField("TITLE", businessPanel.getJobTitle());
    vcard.setOrganizationUnit(businessPanel.getDepartment());
    vcard.setPhoneWork("VOICE", businessPanel.getPhone());
    vcard.setPhoneWork("FAX", businessPanel.getFax());
    vcard.setPhoneWork("PAGER", businessPanel.getPager());
    vcard.setPhoneWork("CELL", businessPanel.getMobile());
    vcard.setField("URL", businessPanel.getWebPage());

    // Save Home Info
    vcard.setAddressFieldHome("STREET", homePanel.getStreetAddress());
    vcard.setAddressFieldHome("LOCALITY", homePanel.getCity());
    vcard.setAddressFieldHome("REGION", homePanel.getState());
    vcard.setAddressFieldHome("PCODE", homePanel.getZipCode());
    vcard.setAddressFieldHome("CTRY", homePanel.getCountry());
    vcard.setPhoneHome("VOICE", homePanel.getPhone());
    vcard.setPhoneHome("FAX", homePanel.getFax());
    vcard.setPhoneHome("PAGER", homePanel.getPager());
    vcard.setPhoneHome("CELL", homePanel.getMobile());

    // Save Avatar
    final File avatarFile = avatarPanel.getAvatarFile();
    byte[] avatarBytes = avatarPanel.getAvatarBytes();

    if (avatarFile != null) {
      try {
        // Make it 48x48
        ImageIcon icon = new ImageIcon(avatarFile.toURI().toURL());
        Image image = icon.getImage();
        image = image.getScaledInstance(-1, 48, Image.SCALE_SMOOTH);
        avatarBytes = GraphicUtils.getBytesFromImage(image);
      } catch (MalformedURLException e) {
        Log.error("Unable to set avatar.", e);
      }
    }

    // If avatar bytes, persist as vcard.
    if (avatarBytes != null) {
      vcard.setAvatar(avatarBytes);
    }

    try {
      final VCardManager vcardManager = SparkManager.getVCardManager();
      vcardManager.setPersonalVCard(vcard);

      vcard.save(SparkManager.getConnection());

      // Notify users.
      if (avatarFile != null || avatarBytes != null) {
        Presence presence = SparkManager.getWorkspace().getStatusBar().getPresence();
        Presence newPresence =
            new Presence(
                presence.getType(),
                presence.getStatus(),
                presence.getPriority(),
                presence.getMode());

        // Change my own presence
        SparkManager.getSessionManager().changePresence(newPresence);

        // Chnage avatar in status bar.
        StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
        statusBar.setAvatar(new ImageIcon(vcard.getAvatar()));
      } else {
        String firstName = vcard.getFirstName();
        String lastName = vcard.getLastName();
        StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
        if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) {
          statusBar.setNickname(firstName + " " + lastName);
        } else if (ModelUtil.hasLength(firstName)) {
          statusBar.setNickname(firstName);
        }

        statusBar.setAvatar(null);
      }

      // Notify listenres
      SparkManager.getVCardManager().notifyVCardListeners();
    } catch (XMPPException e) {
      Log.error(e);
      JOptionPane.showMessageDialog(
          SparkManager.getMainWindow(),
          Res.getString("message.vcard.not.supported"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
    }
  }
コード例 #23
0
  @Override
  public void initialize() {

    if (SystemTray.isSupported()) {

      JMenuItem openMenu = new JMenuItem(Res.getString("menuitem.open"));
      JMenuItem minimizeMenu = new JMenuItem(Res.getString("menuitem.hide"));
      JMenuItem exitMenu = new JMenuItem(Res.getString("menuitem.exit"));
      statusMenu = new JMenu(Res.getString("menuitem.status"));
      JMenuItem logoutMenu = new JMenuItem(Res.getString("menuitem.logout.no.status"));

      SystemTray tray = SystemTray.getSystemTray();
      SparkManager.getNativeManager().addNativeHandler(this);
      ChatManager.getInstance().addChatMessageHandler(chatMessageHandler);
      // XEP-0085 suport (replaces the obsolete XEP-0022)
      org.jivesoftware.smack.chat.ChatManager.getInstanceFor(SparkManager.getConnection())
          .addChatListener(this);

      if (Spark.isLinux()) {
        newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY_LINUX);
        typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY_LINUX);
      } else {
        newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY);
        typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY);
      }

      availableIcon = Default.getImageIcon(Default.TRAY_IMAGE);
      if (Spark.isLinux()) {
        if (availableIcon == null) {
          availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE_LINUX);
          Log.error(availableIcon.toString());
        }
        awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY_LINUX);
        dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND_LINUX);
        offlineIcon = SparkRes.getImageIcon(SparkRes.TRAY_OFFLINE_LINUX);
        connectingIcon = SparkRes.getImageIcon(SparkRes.TRAY_CONNECTING_LINUX);
      } else {
        if (availableIcon == null) {
          availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE);
        }
        awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY);
        dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND);
        offlineIcon = SparkRes.getImageIcon(SparkRes.TRAY_OFFLINE);
        connectingIcon = SparkRes.getImageIcon(SparkRes.TRAY_CONNECTING);
      }

      popupMenu.add(openMenu);
      openMenu.addActionListener(
          new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {
              SparkManager.getMainWindow().setVisible(true);
              SparkManager.getMainWindow().toFront();
            }
          });
      popupMenu.add(minimizeMenu);
      minimizeMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {
              SparkManager.getMainWindow().setVisible(false);
            }
          });
      popupMenu.addSeparator();
      addStatusMessages();
      popupMenu.add(statusMenu);
      statusMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {}
          });

      if (Spark.isWindows()) {
        if (!Default.getBoolean("DISABLE_EXIT")) popupMenu.add(logoutMenu);

        logoutMenu.addActionListener(
            new AbstractAction() {
              private static final long serialVersionUID = 1L;

              @Override
              public void actionPerformed(ActionEvent e) {
                SparkManager.getMainWindow().logout(false);
              }
            });
      }
      // Exit Menu
      exitMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
              SparkManager.getMainWindow().shutdown();
            }
          });
      if (!Default.getBoolean("DISABLE_EXIT")) popupMenu.add(exitMenu);

      /** If connection closed set offline tray image */
      SparkManager.getConnection()
          .addConnectionListener(
              new ConnectionListener() {

                @Override
                public void connected(XMPPConnection xmppConnection) {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void authenticated(XMPPConnection xmppConnection, boolean b) {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void connectionClosed() {
                  trayIcon.setImage(offlineIcon.getImage());
                }

                @Override
                public void connectionClosedOnError(Exception arg0) {
                  trayIcon.setImage(offlineIcon.getImage());
                }

                @Override
                public void reconnectingIn(int arg0) {
                  trayIcon.setImage(connectingIcon.getImage());
                }

                @Override
                public void reconnectionSuccessful() {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void reconnectionFailed(Exception arg0) {
                  trayIcon.setImage(offlineIcon.getImage());
                }
              });

      SparkManager.getSessionManager()
          .addPresenceListener(
              presence -> {
                if (presence.getMode() == Presence.Mode.available) {
                  trayIcon.setImage(availableIcon.getImage());
                } else if (presence.getMode() == Presence.Mode.away
                    || presence.getMode() == Presence.Mode.xa) {
                  trayIcon.setImage(awayIcon.getImage());
                } else if (presence.getMode() == Presence.Mode.dnd) {
                  trayIcon.setImage(dndIcon.getImage());
                } else {
                  trayIcon.setImage(availableIcon.getImage());
                }
              });

      try {

        trayIcon =
            new TrayIcon(
                availableIcon.getImage(), Default.getString(Default.APPLICATION_NAME), null);
        trayIcon.setImageAutoSize(true);

        trayIcon.addMouseListener(
            new MouseListener() {

              @Override
              public void mouseClicked(MouseEvent event) {
                // if we are using double click on tray icon
                if ((!pref.isUsingSingleTrayClick()
                        && event.getButton() == MouseEvent.BUTTON1
                        && event.getClickCount() % 2 == 0)
                    ||
                    // if we using single click on tray icon
                    (pref.isUsingSingleTrayClick()
                        && event.getButton() == MouseEvent.BUTTON1
                        && event.getClickCount() == 1)) {

                  // bring the mainwindow to front
                  if ((SparkManager.getMainWindow().isVisible())
                      && (SparkManager.getMainWindow().getState() == java.awt.Frame.NORMAL)) {
                    SparkManager.getMainWindow().setVisible(false);
                  } else {
                    SparkManager.getMainWindow().setVisible(true);
                    SparkManager.getMainWindow().setState(java.awt.Frame.NORMAL);
                    SparkManager.getMainWindow().toFront();
                  }

                } else if (event.getButton() == MouseEvent.BUTTON1) {
                  SparkManager.getMainWindow().toFront();
                  // SparkManager.getMainWindow().requestFocus();
                } else if (event.getButton() == MouseEvent.BUTTON3) {

                  if (popupMenu.isVisible()) {
                    popupMenu.setVisible(false);
                  } else {

                    double x = MouseInfo.getPointerInfo().getLocation().getX();
                    double y = MouseInfo.getPointerInfo().getLocation().getY();

                    if (Spark.isMac()) {
                      popupMenu.setLocation((int) x, (int) y);
                    } else {
                      popupMenu.setLocation(event.getX(), event.getY());
                    }

                    popupMenu.setInvoker(popupMenu);
                    popupMenu.setVisible(true);
                  }
                }
              }

              @Override
              public void mouseEntered(MouseEvent event) {}

              @Override
              public void mouseExited(MouseEvent event) {}

              @Override
              public void mousePressed(MouseEvent event) {

                // on Mac i would want the window to show when i left-click the Icon
                if (Spark.isMac() && event.getButton() != MouseEvent.BUTTON3) {
                  SparkManager.getMainWindow().setVisible(false);
                  SparkManager.getMainWindow().setVisible(true);
                  SparkManager.getMainWindow().requestFocusInWindow();
                  SparkManager.getMainWindow().bringFrameIntoFocus();
                  SparkManager.getMainWindow().toFront();
                  SparkManager.getMainWindow().requestFocus();
                }
              }

              @Override
              public void mouseReleased(MouseEvent event) {}
            });

        tray.add(trayIcon);
      } catch (Exception e) {
        // Not Supported
      }
    } else {
      Log.error("Tray don't supports on this platform.");
    }
  }