/**
   * Save the handle.
   *
   * <p>If the handleID is -1 then a new handle is created.
   *
   * @param context The current dspace context
   * @param handleID The handle ID, or -1 for a new handle.
   * @param url The handle URL
   * @param resourceTypeID The type of referenced resource
   * @param resourceID ID of referenced resource
   * @return A result
   */
  public static FlowResult processSaveHandle(
      Context context,
      int handleID,
      String handle,
      String url,
      int resourceTypeID,
      int resourceID,
      boolean archiveOldHandle)
      throws SQLException, AuthorizeException, UIException {
    FlowResult result = new FlowResult();
    result.setParameter("handle_id", handleID);

    result.setContinue(false);
    result.setOutcome(false);

    // If we have errors, the form needs to be resubmitted to fix those problems
    if (StringUtils.isEmpty(handle)) {
      result.addError("handle_empty");
    }
    if (resourceTypeID == -1 && resourceID == -1 && StringUtils.isEmpty(url)) {
      result.addError("url_empty");
    } else if (StringUtils.isEmpty(url)) {
      if (resourceTypeID == -1) {
        result.addError("resource_type_id_empty");
      }
      if (resourceID == -1) {
        result.addError("resource_id_empty");
      }
    }

    if (result.getErrors() == null) {

      try {

        Handle h = null;
        if (handleID == -1) {
          h = Handle.create(context, null, handle);
        } else {
          h = Handle.find(context, handleID);
          if (h.getHandle() != handle) {
            HandleManager.changeHandle(context, h.getHandle(), handle, archiveOldHandle);
          }
        }

        h.setHandle(handle);
        h.setURL(url);
        h.setResourceTypeID(resourceTypeID);
        h.setResourceID(resourceID);
        h.update();

        context.commit();

        result.setContinue(true);
        result.setOutcome(true);
        result.setMessage(T_handle_successfully_saved);
      } catch (Exception e) {
        result.setMessage(T_handle_saving_failed);
        log.error(e.getMessage());
        context.abort();
      }
    }

    return result;
  }