private static void writeConfig(
      final ContextManager contextManager, final StoredConfiguration storedConfiguration)
      throws PwmOperationalException, PwmUnrecoverableException {
    ConfigurationReader configReader = contextManager.getConfigReader();
    PwmApplication pwmApplication = contextManager.getPwmApplication();

    try {
      // add a random security key
      storedConfiguration.initNewRandomSecurityKey();

      storedConfiguration.writeConfigProperty(
          StoredConfiguration.ConfigProperty.PROPERTY_KEY_CONFIG_IS_EDITABLE, "true");
      configReader.saveConfiguration(storedConfiguration, pwmApplication, null);

      contextManager.requestPwmApplicationRestart();
    } catch (PwmException e) {
      throw new PwmOperationalException(e.getErrorInformation());
    } catch (Exception e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_INVALID_CONFIG,
              "unable to save configuration: " + e.getLocalizedMessage());
      throw new PwmOperationalException(errorInformation);
    }
  }
  private void restBrowseLdap(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, ServletException, PwmUnrecoverableException {
    final StoredConfiguration storedConfiguration =
        StoredConfiguration.copy(configGuideBean.getStoredConfiguration());
    if (configGuideBean.getStep() == STEP.LDAP_ADMIN) {
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, null);
      storedConfiguration.resetSetting(PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, null);
    }

    final Date startTime = new Date();
    final Map<String, String> inputMap = pwmRequest.readBodyAsJsonStringMap(true);
    final String profile = inputMap.get("profile");
    final String dn = inputMap.containsKey("dn") ? inputMap.get("dn") : "";

    final LdapBrowser ldapBrowser = new LdapBrowser(storedConfiguration);
    final LdapBrowser.LdapBrowseResult result = ldapBrowser.doBrowse(profile, dn);
    ldapBrowser.close();

    LOGGER.trace(
        pwmRequest,
        "performed ldapBrowse operation in "
            + TimeDuration.fromCurrent(startTime).asCompactString()
            + ", result="
            + JsonUtil.serialize(result));

    pwmRequest.outputJsonResult(new RestResultBean(result));
  }
  public static void restUploadConfig(final PwmRequest pwmRequest)
      throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.RUNNING) {
      final String errorMsg = "config upload is not permitted when in running mode";
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] {errorMsg});
      pwmRequest.respondWithError(errorInformation, true);
      return;
    }

    if (ServletFileUpload.isMultipartContent(req)) {
      final InputStream uploadedFile = ServletHelper.readFileUpload(req, "uploadFile");
      if (uploadedFile != null) {
        try {
          final StoredConfiguration storedConfig = StoredConfiguration.fromXml(uploadedFile);
          final List<String> configErrors = storedConfig.validateValues();
          if (configErrors != null && !configErrors.isEmpty()) {
            throw new PwmOperationalException(
                new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, configErrors.get(0)));
          }
          writeConfig(ContextManager.getContextManager(req.getSession()), storedConfig);
          LOGGER.trace(pwmSession, "read config from file: " + storedConfig.toString());
          final RestResultBean restResultBean = new RestResultBean();
          restResultBean.setSuccessMessage("read message");
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          req.getSession().invalidate();
        } catch (PwmException e) {
          final RestResultBean restResultBean =
              RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
          pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
          LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
        }
      } else {
        final ErrorInformation errorInformation =
            new ErrorInformation(
                PwmError.CONFIG_UPLOAD_FAILURE,
                "error reading config file: no file present in upload");
        final RestResultBean restResultBean =
            RestResultBean.fromError(errorInformation, pwmRequest);
        pwmRequest.getPwmResponse().outputJsonResult(restResultBean);
        LOGGER.error(pwmSession, errorInformation.toDebugStr());
      }
    }
  }
  private void restUpdateLdapForm(
      final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, PwmUnrecoverableException {
    final StoredConfiguration storedConfiguration = configGuideBean.getStoredConfiguration();
    final Map<String, String> incomingFormData = pwmRequest.readBodyAsJsonStringMap();

    if (incomingFormData != null) {
      configGuideBean.getFormData().putAll(incomingFormData);
    }

    if (incomingFormData != null
        && incomingFormData.get(PARAM_TEMPLATE_NAME) != null
        && !incomingFormData.get(PARAM_TEMPLATE_NAME).isEmpty()) {
      try {
        final PwmSettingTemplate template =
            PwmSettingTemplate.valueOf(incomingFormData.get(PARAM_TEMPLATE_NAME));
        if (configGuideBean.getSelectedTemplate() != template) {
          LOGGER.debug(
              pwmRequest, "resetting form defaults using " + template.toString() + " template");
          final Map<String, String> defaultForm = defaultForm(template);
          configGuideBean.getFormData().putAll(defaultForm);
          configGuideBean.setSelectedTemplate(template);
          storedConfiguration.setTemplate(template);
          {
            final String settingValue = AppProperty.LDAP_PROMISCUOUS_ENABLE.getKey() + "=true";
            storedConfiguration.writeSetting(
                PwmSetting.APP_PROPERTY_OVERRIDES,
                new StringArrayValue(Collections.singletonList(settingValue)),
                null);
          }
        }
      } catch (Exception e) {
        LOGGER.error("unknown template set request: " + e.getMessage());
      }
    }

    final RestResultBean restResultBean = new RestResultBean();
    pwmRequest.outputJsonResult(restResultBean);
    convertFormToConfiguration(
        storedConfiguration, configGuideBean.getFormData(), incomingFormData);
    // LOGGER.info("config: " + storedConfiguration.toString());
  }
  private void writeConfig(
      final ContextManager contextManager, final ConfigGuideBean configGuideBean)
      throws PwmOperationalException, PwmUnrecoverableException {
    final StoredConfiguration storedConfiguration = configGuideBean.getStoredConfiguration();
    final String configPassword = configGuideBean.getFormData().get(PARAM_CONFIG_PASSWORD);
    if (configPassword != null && configPassword.length() > 0) {
      storedConfiguration.setPassword(configPassword);
    } else {
      storedConfiguration.writeConfigProperty(
          StoredConfiguration.ConfigProperty.PROPERTY_KEY_PASSWORD_HASH, null);
    }

    { // determine Cr Preference setting.
      final String crPref = configGuideBean.getFormData().get(PARAM_CR_STORAGE_PREF);
      if (crPref != null && crPref.length() > 0) {
        storedConfiguration.writeSetting(
            PwmSetting.FORGOTTEN_PASSWORD_WRITE_PREFERENCE, new StringValue(crPref), null);
        storedConfiguration.writeSetting(
            PwmSetting.FORGOTTEN_PASSWORD_READ_PREFERENCE, new StringValue(crPref), null);
      }
    }

    storedConfiguration.readSetting(PwmSetting.APP_PROPERTY_OVERRIDES);
    writeConfig(contextManager, storedConfiguration);
  }
  public static void convertFormToConfiguration(
      final StoredConfiguration storedConfiguration,
      final Map<String, String> ldapForm,
      final Map<String, String> incomingLdapForm)
      throws PwmUnrecoverableException {
    {
      final String newLdapURI = getLdapUrlFromFormConfig(ldapForm);
      final StringArrayValue newValue = new StringArrayValue(Collections.singletonList(newLdapURI));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_SERVER_URLS, LDAP_PROFILE_KEY, newValue, null);
    }

    { // proxy/admin account
      final String ldapAdminDN = ldapForm.get(PARAM_LDAP_ADMIN_DN);
      final String ldapAdminPW = ldapForm.get(PARAM_LDAP_ADMIN_PW);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapAdminDN), null);
      final PasswordValue passwordValue =
          new PasswordValue(PasswordData.forStringValue(ldapAdminPW));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, passwordValue, null);
    }

    // set context based on ldap dn
    if (incomingLdapForm.containsKey(PARAM_LDAP_ADMIN_DN)) {
      final String ldapAdminDN = ldapForm.get(PARAM_LDAP_ADMIN_DN);
      String contextDN = "";
      if (ldapAdminDN != null && ldapAdminDN.contains(",")) {
        contextDN = ldapAdminDN.substring(ldapAdminDN.indexOf(",") + 1, ldapAdminDN.length());
      }
      ldapForm.put(PARAM_LDAP_CONTEXT, contextDN);
    }
    storedConfiguration.writeSetting(
        PwmSetting.LDAP_CONTEXTLESS_ROOT,
        LDAP_PROFILE_KEY,
        new StringArrayValue(Collections.singletonList(ldapForm.get(PARAM_LDAP_CONTEXT))),
        null);

    { // set context based on ldap dn
      final String ldapContext = ldapForm.get(PARAM_LDAP_CONTEXT);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_CONTEXTLESS_ROOT,
          LDAP_PROFILE_KEY,
          new StringArrayValue(Collections.singletonList(ldapContext)),
          null);
    }

    { // set context based on ldap dn
      final String ldapTestUserDN = ldapForm.get(PARAM_LDAP_TEST_USER);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_TEST_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapTestUserDN), null);
    }

    { // set admin query
      final String groupDN = ldapForm.get(PARAM_LDAP_ADMIN_GROUP);
      final List<UserPermission> userPermissions =
          Collections.singletonList(
              new UserPermission(UserPermission.Type.ldapGroup, null, null, groupDN));
      storedConfiguration.writeSetting(
          PwmSetting.QUERY_MATCH_PWM_ADMIN, new UserPermissionValue(userPermissions), null);
    }

    // set context based on ldap dn
    if (incomingLdapForm.containsKey(PARAM_APP_SITEURL)) {
      ldapForm.put(PARAM_APP_SITEURL, incomingLdapForm.get(PARAM_APP_SITEURL));
    }
    storedConfiguration.writeSetting(
        PwmSetting.PWM_SITE_URL, new StringValue(ldapForm.get(PARAM_APP_SITEURL)), null);
  }