/** Handles new incoming object. */
  private void handle(JSONObject incomingObject) {
    if (!incomingObject.containsKey("class")) return;

    try {
      String classField = (String) incomingObject.get("class");

      if (classField.equals("loginko")) {
        showError(null, null, "Unauthorized. Cannot login: "******"errorstring"));

        logger.error("Error login: "******"errorstring"));

        destroy();

        return;
      } else if (classField.equals("login_id_ok")) {
        SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID();

        boolean useSipCredentials = accountID.isClistOptionUseSipCredentials();

        String password;
        if (useSipCredentials) {
          password = SipActivator.getProtocolProviderFactory().loadPassword(accountID);
        } else {
          password = accountID.getClistOptionPassword();
        }

        if (!authorize((String) incomingObject.get("sessionid"), password))
          logger.error("Error login authorization!");

        return;
      } else if (classField.equals("login_pass_ok")) {
        if (!sendCapas((JSONArray) incomingObject.get("capalist")))
          logger.error("Error send capas!");

        return;
      } else if (classField.equals("login_capas_ok")) {
        if (!sendFeatures(
            (String) incomingObject.get("astid"), (String) incomingObject.get("xivo_userid")))
          logger.error("Problem send features get!");

        return;
      } else if (classField.equals("features")) {
        if (!getPhoneList()) logger.error("Problem send get phones!");

        return;
      } else if (classField.equals("phones")) {
        phonesRecieved(incomingObject);
        return;
      } else if (classField.equals("disconn")) {
        destroy();
        return;
      } else {
        if (logger.isTraceEnabled()) logger.trace("unhandled classField: " + incomingObject);
        return;
      }
    } catch (Throwable t) {
      logger.error("Error handling incoming object", t);
    }
  }
  /**
   * Parses the given http response.
   *
   * @param response the http response to parse
   * @return the new account
   */
  private NewAccount parseHttpResponse(String response) {
    NewAccount newAccount = null;
    try {
      JSONObject jsonObject = (JSONObject) JSONValue.parseWithException(response);
      boolean isSuccess = (Boolean) jsonObject.get("success");

      if (isSuccess) {
        newAccount =
            new NewAccount(
                (String) jsonObject.get("sip_address"),
                passField.getPassword(),
                null,
                (String) jsonObject.get("outbound_proxy"));

        String xcapRoot = (String) jsonObject.get("xcap_root");

        // as sip2sip adds @sip2sip.info at the end of the
        // xcap_uri but doesn't report it in resullt after
        // creating account, we add it
        String domain = null;
        int delimIndex = newAccount.getUserName().indexOf("@");
        if (delimIndex != -1) {
          domain = newAccount.getUserName().substring(delimIndex);
        }
        if (domain != null) {
          if (xcapRoot.endsWith("/"))
            xcapRoot = xcapRoot.substring(0, xcapRoot.length() - 1) + domain;
          else xcapRoot += domain;
        }

        newAccount.setXcapRoot(xcapRoot);
      } else {
        showErrorMessage((String) jsonObject.get("error_message"));
      }
    } catch (Throwable e1) {
      if (logger.isInfoEnabled()) logger.info("Failed Json parsing.", e1);
    }

    return newAccount;
  }
  /**
   * parses received phones list and creates/resolves groups and contacts
   *
   * @param objReceived the obj with data.
   */
  private void phonesRecieved(JSONObject objReceived) {
    try {
      if (!objReceived.get("function").equals("sendlist") || !objReceived.containsKey("payload"))
        return;

      JSONObject payload = (JSONObject) objReceived.get("payload");
      /*
       * FIXME The following contains two very inefficient Map-iterating
       * loops.
       */
      Iterator iter = payload.keySet().iterator();
      List<JSONObject> phoneList = new ArrayList<JSONObject>();
      while (iter.hasNext()) {
        JSONObject obj = (JSONObject) payload.get(iter.next());
        Iterator phonesIter = obj.keySet().iterator();
        while (phonesIter.hasNext()) phoneList.add((JSONObject) obj.get(phonesIter.next()));
      }

      for (JSONObject phone : phoneList) {
        try {
          // don't handle non sip phones
          if (!((String) phone.get("tech")).equalsIgnoreCase("sip")) continue;

          String groupName = (String) phone.get("context");

          ContactGroupSipImpl parentGroup = findGroupByName(groupName);

          if (parentGroup == null) {
            parentGroup = new ContactGroupSipImpl(groupName, sipProvider);
            parentGroup.setPersistent(true);
            getRootGroup().addSubgroup(parentGroup);

            fireGroupEvent(parentGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT);
          }

          String number = (String) phone.get("number");

          Address address = sipProvider.parseAddressString(number);

          // if the contact is already in the contact list
          ContactSipImpl contact = parentOperationSet.resolveContactID(address.toString());

          if (contact == null) {
            contact = new ContactSipImpl(address, sipProvider);
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);
            parentGroup.addContact(contact);

            fireContactAdded(parentGroup, contact);
          } else {
            contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname"));
            contact.setResolved(true);

            fireContactResolved(parentGroup, contact);
          }
        } catch (Throwable t) {
          logger.error("Error parsing " + phone);
        }
      }
    } catch (Throwable t) {
      logger.error("Error init list from server", t);
    }
  }