@Override
  public void handle(Request request, Response response) throws Exception {
    if (settings.getBoolean(CorePropertyDefinitions.ORGANIZATIONS_ANYONE_CAN_CREATE)) {
      userSession.checkLoggedIn();
    } else {
      userSession.checkIsRoot();
    }

    String name = wsSupport.getAndCheckMandatoryName(request);
    String requestKey = getAndCheckKey(request);
    String key = useOrGenerateKey(requestKey, name);
    wsSupport.getAndCheckDescription(request);
    wsSupport.getAndCheckUrl(request);
    wsSupport.getAndCheckAvatar(request);

    try (DbSession dbSession = dbClient.openSession(false)) {
      checkKeyIsNotUsed(dbSession, key, requestKey, name);

      OrganizationDto dto = createOrganizationDto(request, name, key);
      dbClient.organizationDao().insert(dbSession, dto);
      GroupDto group = createOwnersGroup(dbSession, dto);
      addCurrentUserToGroup(dbSession, group);
      dbSession.commit();

      writeResponse(request, response, dto);
    }
  }
  @Override
  public void define(WebService.NewController context) {
    WebService.NewAction action =
        context
            .createAction(ACTION)
            .setPost(true)
            .setDescription(
                "Create an organization.<br />"
                    + "Requires 'Administer System' permission unless any logged in user is allowed to create an organization (see appropriate setting).")
            .setResponseExample(getClass().getResource("example-create.json"))
            .setInternal(true)
            .setSince("6.2")
            .setHandler(this);

    action
        .createParam(PARAM_KEY)
        .setRequired(false)
        .setDescription(
            "Key of the organization. <br />"
                + "The key is unique to the whole SonarQube. <br/>"
                + "When not specified, the key is computed from the name. <br />"
                + "Otherwise, it must be between 2 and 32 chars long. All chars must be lower-case letters (a to z), digits or dash (but dash can neither be trailing nor heading)")
        .setExampleValue("foo-company");

    wsSupport.addOrganizationDetailsParams(action, true);
  }
 private void writeResponse(Request request, Response response, OrganizationDto dto) {
   writeProtobuf(
       CreateWsResponse.newBuilder().setOrganization(wsSupport.toOrganization(dto)).build(),
       request,
       response);
 }