/**
   * Update an existing client
   *
   * @param id
   * @param jsonString
   * @param m
   * @param principal
   * @return
   */
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.PUT,
      consumes = "application/json",
      produces = "application/json")
  public String apiUpdateClient(
      @PathVariable("id") Long id, @RequestBody String jsonString, Model m, Authentication auth) {

    JsonObject json = null;
    ClientDetailsEntity client = null;

    try {
      // parse the client passed in (from JSON) and fetch the old client from the store
      json = parser.parse(jsonString).getAsJsonObject();
      client = gson.fromJson(json, ClientDetailsEntity.class);
    } catch (JsonSyntaxException e) {
      logger.error("apiUpdateClient failed due to JsonSyntaxException", e);
      m.addAttribute("code", HttpStatus.BAD_REQUEST);
      m.addAttribute(
          "errorMessage",
          "Could not update client. The server encountered a JSON syntax exception. Contact a system administrator for assistance.");
      return "jsonErrorView";
    } catch (IllegalStateException e) {
      logger.error("apiUpdateClient failed due to IllegalStateException", e);
      m.addAttribute("code", HttpStatus.BAD_REQUEST);
      m.addAttribute(
          "errorMessage",
          "Could not update client. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance.");
      return "jsonErrorView";
    }

    ClientDetailsEntity oldClient = clientService.getClientById(id);

    if (oldClient == null) {
      logger.error("apiUpdateClient failed; client with id " + id + " could not be found.");
      m.addAttribute("code", HttpStatus.NOT_FOUND);
      m.addAttribute(
          "errorMessage",
          "Could not update client. The requested client with id " + id + "could not be found.");
      return "jsonErrorView";
    }

    // if they leave the client identifier empty, force it to be generated
    if (Strings.isNullOrEmpty(client.getClientId())) {
      client = clientService.generateClientId(client);
    }

    // if they've asked for us to generate a client secret, do so here
    if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean()) {
      client = clientService.generateClientSecret(client);
    }

    // set owners as current logged in user
    // try to look up a user based on the principal's name
    if (client.getContacts() == null || client.getContacts().isEmpty()) {
      UserInfo user = userInfoService.getByUsername(auth.getName());
      if (user != null && user.getEmail() != null) {
        client.setContacts(Sets.newHashSet(user.getEmail()));
      }
    }

    ClientDetailsEntity newClient = clientService.updateClient(oldClient, client);
    m.addAttribute("entity", newClient);

    if (isAdmin(auth)) {
      return "clientEntityViewAdmins";
    } else {
      return "clientEntityViewUsers";
    }
  }
  /**
   * Update the metainformation for a given client.
   *
   * @param clientId
   * @param jsonString
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + OAuth2AccessTokenEntity.REGISTRATION_TOKEN_SCOPE
          + "')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.PUT,
      produces = "application/json",
      consumes = "application/json")
  public String updateClient(
      @PathVariable("id") String clientId,
      @RequestBody String jsonString,
      Model m,
      OAuth2Authentication auth) {

    ClientDetailsEntity newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    ClientDetailsEntity oldClient = clientService.loadClientByClientId(clientId);

    if (newClient != null
        && oldClient != null // we have an existing client and the new one parsed
        && oldClient
            .getClientId()
            .equals(
                auth.getOAuth2Request()
                    .getClientId()) // the client passed in the URI matches the one in the auth
        && oldClient
            .getClientId()
            .equals(
                newClient.getClientId()) // the client passed in the body matches the one in the URI
    ) {

      // a client can't ask to update its own client secret to any particular value
      newClient.setClientSecret(oldClient.getClientSecret());

      // we need to copy over all of the local and SECOAUTH fields
      newClient.setAccessTokenValiditySeconds(oldClient.getAccessTokenValiditySeconds());
      newClient.setIdTokenValiditySeconds(oldClient.getIdTokenValiditySeconds());
      newClient.setRefreshTokenValiditySeconds(oldClient.getRefreshTokenValiditySeconds());
      newClient.setDynamicallyRegistered(true); // it's still dynamically registered
      newClient.setAllowIntrospection(oldClient.isAllowIntrospection());
      newClient.setAuthorities(oldClient.getAuthorities());
      newClient.setClientDescription(oldClient.getClientDescription());
      newClient.setCreatedAt(oldClient.getCreatedAt());
      newClient.setReuseRefreshToken(oldClient.isReuseRefreshToken());

      // set of scopes that are OK for clients to dynamically register for
      Set<SystemScope> dynScopes = scopeService.getDynReg();

      // scopes that the client is asking for
      Set<SystemScope> requestedScopes = scopeService.fromStrings(newClient.getScope());

      // the scopes that the client can have must be a subset of the dynamically allowed scopes
      Set<SystemScope> allowedScopes = Sets.intersection(dynScopes, requestedScopes);

      // make sure that the client doesn't ask for scopes it can't have
      newClient.setScope(scopeService.toStrings(allowedScopes));

      try {
        // save the client
        ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient);

        // we return the token that we got in
        // TODO: rotate this after some set amount of time
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
        OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue());

        // TODO: urlencode the client id for safety?
        RegisteredClient registered =
            new RegisteredClient(
                savedClient,
                token.getValue(),
                config.getIssuer() + "register/" + savedClient.getClientId());

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute("code", HttpStatus.OK); // http 200

        return "clientInformationResponseView";
      } catch (IllegalArgumentException e) {
        logger.error("Couldn't save client", e);
        m.addAttribute("code", HttpStatus.BAD_REQUEST);

        return "httpCodeView";
      }
    } else {
      // client mismatch
      logger.error(
          "readClientConfiguration failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute("code", HttpStatus.FORBIDDEN); // http 403

      return "httpCodeView";
    }
  }
  /**
   * Update the metainformation for a given client.
   *
   * @param clientId
   * @param jsonString
   * @param m
   * @param auth
   * @return
   */
  @PreAuthorize(
      "hasRole('ROLE_CLIENT') and #oauth2.hasScope('"
          + SystemScopeService.RESOURCE_TOKEN_SCOPE
          + "')")
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.PUT,
      produces = MediaType.APPLICATION_JSON_VALUE,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public String updateProtectedResource(
      @PathVariable("id") String clientId,
      @RequestBody String jsonString,
      Model m,
      OAuth2Authentication auth) {

    ClientDetailsEntity newClient = null;
    try {
      newClient = ClientDetailsEntityJsonProcessor.parse(jsonString);
    } catch (JsonSyntaxException e) {
      // bad parse
      // didn't parse, this is a bad request
      logger.error("updateProtectedResource failed; submitted JSON is malformed");
      m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400
      return HttpCodeView.VIEWNAME;
    }

    ClientDetailsEntity oldClient = clientService.loadClientByClientId(clientId);

    if (newClient != null
        && oldClient != null // we have an existing client and the new one parsed
        && oldClient
            .getClientId()
            .equals(
                auth.getOAuth2Request()
                    .getClientId()) // the client passed in the URI matches the one in the auth
        && oldClient
            .getClientId()
            .equals(
                newClient.getClientId()) // the client passed in the body matches the one in the URI
    ) {

      // a client can't ask to update its own client secret to any particular value
      newClient.setClientSecret(oldClient.getClientSecret());

      newClient.setCreatedAt(oldClient.getCreatedAt());

      // no grant types are allowed
      newClient.setGrantTypes(new HashSet<String>());
      newClient.setResponseTypes(new HashSet<String>());
      newClient.setRedirectUris(new HashSet<String>());

      // don't issue tokens to this client
      newClient.setAccessTokenValiditySeconds(0);
      newClient.setIdTokenValiditySeconds(0);
      newClient.setRefreshTokenValiditySeconds(0);

      // clear out unused fields
      newClient.setDefaultACRvalues(new HashSet<String>());
      newClient.setDefaultMaxAge(null);
      newClient.setIdTokenEncryptedResponseAlg(null);
      newClient.setIdTokenEncryptedResponseEnc(null);
      newClient.setIdTokenSignedResponseAlg(null);
      newClient.setInitiateLoginUri(null);
      newClient.setPostLogoutRedirectUris(null);
      newClient.setRequestObjectSigningAlg(null);
      newClient.setRequireAuthTime(null);
      newClient.setReuseRefreshToken(false);
      newClient.setSectorIdentifierUri(null);
      newClient.setSubjectType(null);
      newClient.setUserInfoEncryptedResponseAlg(null);
      newClient.setUserInfoEncryptedResponseEnc(null);
      newClient.setUserInfoSignedResponseAlg(null);

      // this client has been dynamically registered (obviously)
      newClient.setDynamicallyRegistered(true);

      // this client has access to the introspection endpoint
      newClient.setAllowIntrospection(true);

      // do validation on the fields
      try {
        newClient = validateScopes(newClient);
        newClient = validateAuth(newClient);
      } catch (ValidationException ve) {
        // validation failed, return an error
        m.addAttribute(JsonErrorView.ERROR, ve.getError());
        m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription());
        m.addAttribute(HttpCodeView.CODE, ve.getStatus());
        return JsonErrorView.VIEWNAME;
      }

      try {
        // save the client
        ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient);

        // possibly update the token
        OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient);

        RegisteredClient registered =
            new RegisteredClient(
                savedClient,
                token.getValue(),
                config.getIssuer()
                    + "resource/"
                    + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8"));

        // send it all out to the view
        m.addAttribute("client", registered);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.OK); // http 200

        return ClientInformationResponseView.VIEWNAME;
      } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding", e);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        return HttpCodeView.VIEWNAME;
      } catch (IllegalArgumentException e) {
        logger.error("Couldn't save client", e);

        m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata");
        m.addAttribute(
            JsonErrorView.ERROR_MESSAGE,
            "Unable to save client due to invalid or inconsistent metadata.");
        m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400

        return JsonErrorView.VIEWNAME;
      }
    } else {
      // client mismatch
      logger.error(
          "updateProtectedResource"
              + " failed, client ID mismatch: "
              + clientId
              + " and "
              + auth.getOAuth2Request().getClientId()
              + " do not match.");
      m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403

      return HttpCodeView.VIEWNAME;
    }
  }