/**
   * Returns the Clearspace username of the user by id.
   *
   * @param id ID to retrieve Username of.
   * @return The username of the user in Clearspace.
   * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found.
   */
  protected String getUsernameByID(Long id) throws UserNotFoundException {
    // Checks if it is in the cache
    if (usernameCache.containsKey(id)) {
      return usernameCache.get(id);
    }

    // Gets the user's ID from Clearspace
    try {
      String path = ClearspaceUserProvider.USER_URL_PREFIX + "usersByID/" + id;
      Element element =
          executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

      String username =
          WSUtils.getElementText(
              element.selectSingleNode("return"), "username"); // TODO: is this right?

      // Escape the username so that it can be used as a JID.
      username = JID.escapeNode(username);

      usernameCache.put(id, username);

      return username;
    } catch (UserNotFoundException unfe) {
      // It is a supported exception, throw it again
      throw unfe;
    } catch (Exception e) {
      // It is not a supported exception, wrap it into a UserNotFoundException
      throw new UserNotFoundException("Unexpected error", e);
    }
  }
 public void componentInfoReceived(IQ iq) {
   // Check if it's a Clearspace component
   boolean isClearspace = false;
   Element childElement = iq.getChildElement();
   for (Iterator it = childElement.elementIterator("identity"); it.hasNext(); ) {
     Element identity = (Element) it.next();
     if ("component".equals(identity.attributeValue("category"))
         && "clearspace".equals(identity.attributeValue("type"))) {
       isClearspace = true;
     }
   }
   // If component is Clearspace then keep track of the component
   if (isClearspace) {
     clearspaces.add(iq.getFrom().getDomain());
   }
 }
  private void updateClearspaceSharedSecret(String newSecret) {

    try {
      String path = IM_URL_PREFIX + "updateSharedSecret/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("updateSharedSecret");
      rootE.addElement("newSecret").setText(newSecret);

      executeRequest(POST, path, groupDoc.asXML());
    } catch (UnauthorizedException ue) {
      Log.error("Error updating the password of Clearspace", ue);
    } catch (Exception e) {
      Log.error("Error updating the password of Clearspace", e);
    }
  }
  private void updateClearspaceClientSettings() {
    String xmppBoshSslPort = "0";
    String xmppBoshPort = "0";
    String xmppPort =
        String.valueOf(XMPPServer.getInstance().getConnectionManager().getClientListenerPort());
    if (JiveGlobals.getBooleanProperty(
        HttpBindManager.HTTP_BIND_ENABLED, HttpBindManager.HTTP_BIND_ENABLED_DEFAULT)) {
      int boshSslPort = HttpBindManager.getInstance().getHttpBindSecurePort();
      int boshPort = HttpBindManager.getInstance().getHttpBindUnsecurePort();
      try {
        if (HttpBindManager.getInstance().isHttpsBindActive()
            && LocalClientSession.getTLSPolicy()
                != org.jivesoftware.openfire.Connection.TLSPolicy.disabled) {
          xmppBoshSslPort = String.valueOf(boshSslPort);
        }
      } catch (Exception e) {
        // Exception while working with certificate
        Log.debug(
            "Error while checking SSL certificate.  Instructing Clearspace not to use SSL port.");
      }
      if (HttpBindManager.getInstance().isHttpBindActive() && boshPort > 0) {
        xmppBoshPort = String.valueOf(boshPort);
      }
    }

    try {
      String path = CHAT_URL_PREFIX + "updateClientSettings/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("updateClientSettings");
      rootE.addElement("boshSslPort").setText(xmppBoshSslPort);
      rootE.addElement("boshPort").setText(xmppBoshPort);
      rootE.addElement("tcpPort").setText(xmppPort);

      executeRequest(POST, path, groupDoc.asXML());
    } catch (UnauthorizedException ue) {
      Log.error("Error updating the client settings of Clearspace", ue);
    } catch (Exception e) {
      Log.error("Error updating the client settings of Clearspace", e);
    }
  }
  /**
   * Returns the Clearspace user id the user by username.
   *
   * @param username Username to retrieve ID of.
   * @return The ID number of the user in Clearspace.
   * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found.
   */
  protected long getUserID(String username) throws UserNotFoundException {
    // Gets the part before of @ of the username param
    if (username.contains("@")) {
      // User's id are only for local users
      if (!XMPPServer.getInstance().isLocal(new JID(username))) {
        throw new UserNotFoundException("Cannot load user of remote server: " + username);
      }
      username = username.substring(0, username.lastIndexOf("@"));
    }

    // Checks if it is in the cache
    if (userIDCache.containsKey(username)) {
      return userIDCache.get(username);
    }

    // Un-escape username.
    String unescapedUsername = JID.unescapeNode(username);
    // Encode potentially non-ASCII characters
    unescapedUsername = URLUTF8Encoder.encode(unescapedUsername);
    // Gets the user's ID from Clearspace
    try {
      String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/" + unescapedUsername;
      Element element =
          executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

      Long id = Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID"));

      userIDCache.put(username, id);

      return id;
    } catch (UserNotFoundException unfe) {
      // It is a supported exception, throw it again
      throw unfe;
    } catch (Exception e) {
      // It is not a supported exception, wrap it into a UserNotFoundException
      throw new UserNotFoundException("Unexpected error", e);
    }
  }
  /**
   * Returns the Clearspace group id of the group.
   *
   * @param groupname Name of the group to retrieve ID of.
   * @return The ID number of the group in Clearspace.
   * @throws org.jivesoftware.openfire.group.GroupNotFoundException If the group was not found.
   */
  protected long getGroupID(String groupname) throws GroupNotFoundException {
    if (groupIDCache.containsKey(groupname)) {
      return groupIDCache.get(groupname);
    }
    try {
      // Encode potentially non-ASCII characters
      groupname = URLUTF8Encoder.encode(groupname);
      String path = ClearspaceGroupProvider.URL_PREFIX + "groups/" + groupname;
      Element element =
          executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path);

      Long id = Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID"));
      // Saves it into the cache
      groupIDCache.put(groupname, id);

      return id;
    } catch (GroupNotFoundException gnfe) {
      // It is a supported exception, throw it again
      throw gnfe;
    } catch (Exception e) {
      // It is not a supported exception, wrap it into a GroupNotFoundException
      throw new GroupNotFoundException("Unexpected error", e);
    }
  }
  /**
   * If CS throws an exception it handled and transalated to a Openfire exception if possible. This
   * is done using <code>exceptionMap</code> that has a mapping from CS to OF. If no mapping is
   * found then it tries to instantiete the original exception. If this fails it throws a <code>
   * Exception</code> with the message of the CS exception.
   *
   * @param response the response from CS to check if it is an exception message.
   * @throws Exception if the response is an exception message.
   */
  private void checkFault(Element response) throws Exception {
    Node node = response.selectSingleNode("ns1:faultstring");
    if (node != null) {
      String exceptionText = node.getText();

      // Text accepted samples:
      // 'java.lang.Exception: Exception message'
      // 'java.lang.Exception'

      // Get the exception class and message if any
      int index = exceptionText.indexOf(":");
      String className;
      String message;
      // If there is no message, save the class only
      if (index == -1) {
        className = exceptionText;
        message = null;
      } else {
        // Else save both
        className = exceptionText.substring(0, index);
        message = exceptionText.substring(index + 2);
      }

      // Map the exception to a Openfire one, if possible
      if (exceptionMap.containsKey(className)) {
        className = exceptionMap.get(className);
      }

      // Tries to create an instance with the message
      Exception exception;
      try {
        Class exceptionClass = Class.forName(className);
        if (message == null) {
          exception = (Exception) exceptionClass.newInstance();
        } else {
          Constructor constructor = exceptionClass.getConstructor(String.class);
          exception = (Exception) constructor.newInstance(message);
        }
      } catch (Exception e) {
        // failed to create an specific exception, creating a standard one.
        exception = new Exception(exceptionText);
      }

      throw exception;
    }
  }
  private synchronized void doConfigClearspace() throws UnauthorizedException {

    Log.debug("Starting Clearspace configuration.");

    List<String> bindInterfaces = getServerInterfaces();
    if (bindInterfaces.size() == 0) {
      // We aren't up and running enough to tell Clearspace what interfaces to bind to.
      Log.debug("No bind interfaces found to config Clearspace");
      throw new IllegalStateException("There are no binding interfaces.");
    }

    try {

      XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

      String path = IM_URL_PREFIX + "configureComponent/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("configureComponent");
      Element domainE = rootE.addElement("domain");
      domainE.setText(serverInfo.getXMPPDomain());
      for (String bindInterface : bindInterfaces) {
        Element hostsE = rootE.addElement("hosts");
        hostsE.setText(bindInterface);
      }
      Element portE = rootE.addElement("port");
      portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

      Log.debug(
          "Trying to configure Clearspace with: Domain: "
              + serverInfo.getXMPPDomain()
              + ", hosts: "
              + bindInterfaces.toString()
              + ", port: "
              + port);

      executeRequest(POST, path, rootE.asXML());

      // Done, Clearspace was configured correctly, clear the task
      Log.debug("Clearspace was configured, stopping the task.");
      TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
      configClearspaceTask = null;

    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }