/**
   * Creates a new registration in the server. If it exists, updates its information
   *
   * @param registration The registration to create
   * @return The created registration
   * @throws Exception
   */
  private Registration registerInternal(Registration registration) throws Exception {

    if (mIsRefreshNeeded) {
      String pNSHandle = mSharedPreferences.getString(STORAGE_PREFIX + PNS_HANDLE_KEY, "");

      if (isNullOrWhiteSpace(pNSHandle)) {
        pNSHandle = registration.getPNSHandle();
      }

      refreshRegistrationInformation(pNSHandle);
    }

    String registrationId = retrieveRegistrationId(registration.getName());
    if (isNullOrWhiteSpace(registrationId)) {
      registrationId = createRegistrationId();
    }

    registration.setRegistrationId(registrationId);

    try {
      return upsertRegistrationInternal(registration);
    } catch (RegistrationGoneException e) {
      // if we get an RegistrationGoneException (410) from service, we will recreate registration id
      // and will try to do upsert one more time.
    }

    registrationId = createRegistrationId();
    registration.setRegistrationId(registrationId);
    return upsertRegistrationInternal(registration);
  }