コード例 #1
0
  public static void incrementStat(final PwmApplication pwmApplication, final Statistic statistic) {
    if (pwmApplication == null) {
      LOGGER.error(
          "skipping requested statistic increment of " + statistic + " due to null pwmApplication");
      return;
    }

    final StatisticsManager statisticsManager = pwmApplication.getStatisticsManager();
    if (statisticsManager == null) {
      LOGGER.error(
          "skipping requested statistic increment of "
              + statistic
              + " due to null statisticsManager");
      return;
    }

    if (statisticsManager.status() != STATUS.OPEN) {
      LOGGER.trace(
          "skipping requested statistic increment of "
              + statistic
              + " due to StatisticsManager being closed");
      return;
    }

    statisticsManager.incrementValue(statistic);
  }
コード例 #2
0
ファイル: PasswordUtility.java プロジェクト: ldchrist/pwm
  private static void invokePostChangePasswordActions(
      final PwmSession pwmSession, final String newPassword) throws PwmUnrecoverableException {
    final List<PostChangePasswordAction> postChangePasswordActions =
        pwmSession.getUserSessionDataCacheBean().removePostChangePasswordActions();
    if (postChangePasswordActions == null || postChangePasswordActions.isEmpty()) {
      LOGGER.trace(pwmSession, "no post change password actions pending from previous operations");
      return;
    }

    for (final PostChangePasswordAction postChangePasswordAction : postChangePasswordActions) {
      try {
        postChangePasswordAction.doAction(pwmSession, newPassword);
      } catch (PwmUnrecoverableException e) {
        LOGGER.error(
            pwmSession,
            "error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage());
        throw e;
      } catch (Exception e) {
        LOGGER.error(
            pwmSession,
            "unexpected error during post change password action '"
                + postChangePasswordAction.getLabel()
                + "' "
                + e.getMessage(),
            e);
        final ErrorInformation errorInfo =
            new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
        throw new PwmUnrecoverableException(errorInfo);
      }
    }
  }
コード例 #3
0
ファイル: H2_LocalDB.java プロジェクト: CherifSy/pwm
  @Override
  void closeConnection(final Connection connection) throws SQLException {

    if (aggressiveCompact) {
      CallableStatement statement = null;
      try {
        LOCK.writeLock().lock();
        final java.util.Date start = new java.util.Date();
        LOGGER.trace("beginning shutdown compact");
        statement = dbConnection.prepareCall("SHUTDOWN COMPACT");
        statement.execute();
        LOGGER.trace(
            "completed shutdown compact in " + TimeDuration.fromCurrent(start).asCompactString());
      } catch (SQLException ex) {
        LOGGER.error("error during shutdown compact: " + ex.getMessage());
      } finally {
        close(statement);
        LOCK.writeLock().unlock();
      }
    }

    try {
      connection.close();
      if (driver != null) {
        DriverManager.deregisterDriver(driver);
        driver = null;
      }
    } catch (Exception e) {
      LOGGER.error("error during H2 shutdown: " + e.getMessage());
    }
  }
コード例 #4
0
  private void doGenerateSupportZip(final PwmRequest pwmRequest)
      throws IOException, ServletException {
    final PwmResponse resp = pwmRequest.getPwmResponse();
    resp.setHeader(
        PwmConstants.HttpHeader.ContentDisposition,
        "attachment;filename=" + PwmConstants.PWM_APP_NAME + "-Support.zip");
    resp.setContentType(PwmConstants.ContentTypeValue.zip);

    final String pathPrefix = PwmConstants.PWM_APP_NAME + "-Support" + "/";

    ZipOutputStream zipOutput = null;
    try {
      zipOutput = new ZipOutputStream(resp.getOutputStream(), PwmConstants.DEFAULT_CHARSET);
      DebugItemGenerator.outputZipDebugFile(pwmRequest, zipOutput, pathPrefix);
    } catch (Exception e) {
      LOGGER.error(pwmRequest, "error during zip debug building: " + e.getMessage());
    } finally {
      if (zipOutput != null) {
        try {
          zipOutput.close();
        } catch (Exception e) {
          LOGGER.error(pwmRequest, "error during zip debug closing: " + e.getMessage());
        }
      }
    }
  }
コード例 #5
0
ファイル: PwmApplication.java プロジェクト: Alqobais/pwm
  public void shutdown() {
    LOGGER.warn("shutting down");
    {
      // send system audit event
      final SystemAuditRecord auditRecord =
          SystemAuditRecord.create(AuditEvent.SHUTDOWN, null, getInstanceID());
      try {
        getAuditManager().submit(auditRecord);
      } catch (PwmException e) {
        LOGGER.warn("unable to submit alert event " + JsonUtil.serialize(auditRecord));
      }
    }

    {
      final List<Class> reverseServiceList = new ArrayList<Class>(PWM_SERVICE_CLASSES);
      Collections.reverse(reverseServiceList);
      for (final Class serviceClass : reverseServiceList) {
        if (pwmServices.containsKey(serviceClass)) {
          LOGGER.trace("closing service " + serviceClass.getName());
          final PwmService loopService = pwmServices.get(serviceClass);
          LOGGER.trace("successfully closed service " + serviceClass.getName());
          try {
            loopService.close();
          } catch (Exception e) {
            LOGGER.error(
                "error closing " + loopService.getClass().getSimpleName() + ": " + e.getMessage(),
                e);
          }
        }
      }
    }

    if (localDBLogger != null) {
      try {
        localDBLogger.close();
      } catch (Exception e) {
        LOGGER.error("error closing localDBLogger: " + e.getMessage(), e);
      }
      localDBLogger = null;
    }

    if (localDB != null) {
      try {
        localDB.close();
      } catch (Exception e) {
        LOGGER.fatal("error closing localDB: " + e, e);
      }
      localDB = null;
    }

    LOGGER.info(
        PwmConstants.PWM_APP_NAME
            + " "
            + PwmConstants.SERVLET_VERSION
            + " closed for bidness, cya!");
  }
コード例 #6
0
ファイル: ConfigGuideServlet.java プロジェクト: aboieriu/pwm
  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 StoredConfigurationImpl storedConfig =
              StoredConfigurationImpl.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());
      }
    }
  }
コード例 #7
0
ファイル: PasswordUtility.java プロジェクト: ldchrist/pwm
  private static Date determinePwdLastModified(
      final PwmApplication pwmApplication,
      final SessionLabel sessionLabel,
      final ChaiUser theUser,
      final UserIdentity userIdentity)
      throws ChaiUnavailableException, PwmUnrecoverableException {
    // fetch last password modification time from pwm last update attribute operation
    try {
      final Date chaiReadDate = theUser.readPasswordModificationDate();
      if (chaiReadDate != null) {
        LOGGER.trace(
            sessionLabel,
            "read last user password change timestamp (via chai) as: "
                + PwmConstants.DEFAULT_DATETIME_FORMAT.format(chaiReadDate));
        return chaiReadDate;
      }
    } catch (ChaiOperationException e) {
      LOGGER.error(
          sessionLabel,
          "unexpected error reading password last modified timestamp: " + e.getMessage());
    }

    final LdapProfile ldapProfile =
        pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID());
    final String pwmLastSetAttr =
        ldapProfile.readSettingAsString(PwmSetting.PASSWORD_LAST_UPDATE_ATTRIBUTE);
    if (pwmLastSetAttr != null && pwmLastSetAttr.length() > 0) {
      try {
        final Date pwmPwdLastModified = theUser.readDateAttribute(pwmLastSetAttr);
        LOGGER.trace(
            sessionLabel,
            "read pwmPasswordChangeTime as: "
                + (pwmPwdLastModified == null
                    ? "n/a"
                    : PwmConstants.DEFAULT_DATETIME_FORMAT.format(pwmPwdLastModified)));
        return pwmPwdLastModified;
      } catch (ChaiOperationException e) {
        LOGGER.error(
            sessionLabel,
            "error parsing password last modified PWM password value for user "
                + theUser.getEntryDN()
                + "; error: "
                + e.getMessage());
      }
    }

    LOGGER.debug(sessionLabel, "unable to determine time of user's last password modification");
    return null;
  }
コード例 #8
0
ファイル: ConfigGuideServlet.java プロジェクト: aboieriu/pwm
 public static SchemaOperationResult extendSchema(
     ConfigGuideBean configGuideBean, final boolean doSchemaExtension) {
   final Map<String, String> form = configGuideBean.getFormData();
   final boolean ldapServerSecure = "true".equalsIgnoreCase(form.get(PARAM_LDAP_SECURE));
   final String ldapUrl =
       "ldap"
           + (ldapServerSecure ? "s" : "")
           + "://"
           + form.get(PARAM_LDAP_HOST)
           + ":"
           + form.get(PARAM_LDAP_PORT);
   try {
     final ChaiConfiguration chaiConfiguration =
         new ChaiConfiguration(
             ldapUrl, form.get(PARAM_LDAP_PROXY_DN), form.get(PARAM_LDAP_PROXY_PW));
     chaiConfiguration.setSetting(ChaiSetting.PROMISCUOUS_SSL, "true");
     final ChaiProvider chaiProvider = ChaiProviderFactory.createProvider(chaiConfiguration);
     if (doSchemaExtension) {
       return SchemaManager.extendSchema(chaiProvider);
     } else {
       return SchemaManager.checkExistingSchema(chaiProvider);
     }
   } catch (Exception e) {
     LOGGER.error("unable to create schema extender object: " + e.getMessage());
     return null;
   }
 }
コード例 #9
0
ファイル: NMASUAWSOperator.java プロジェクト: dragonarmor/pwm
  @Override
  public ResponseInfoBean readResponseInfo(
      final ChaiUser theUser, final UserIdentity userIdentity, final String userGUID)
      throws PwmUnrecoverableException {
    final ResponseSet responseSet = readResponsesFromNovellUA(pwmApplication, theUser);
    if (responseSet == null) {
      return null;
    }

    final Map<Challenge, String> crMap = new LinkedHashMap<>();
    final Map<Challenge, String> helpdeskCrMap = new LinkedHashMap<>();
    try {
      for (final Challenge loopChallenge : responseSet.getChallengeSet().getChallenges()) {
        crMap.put(loopChallenge, "");
      }
      for (final Challenge loopChallenge : responseSet.getHelpdeskResponses().keySet()) {
        helpdeskCrMap.put(loopChallenge, "");
      }

      return new ResponseInfoBean(
          crMap,
          helpdeskCrMap,
          PwmConstants.DEFAULT_LOCALE,
          responseSet.getChallengeSet().getMinRandomRequired(),
          responseSet.getChallengeSet().getIdentifier(),
          DataStorageMethod.NMASUAWS,
          null);
    } catch (ChaiValidationException e) {
      LOGGER.error(
          "unexpected error converting NMASUserAppWebService ResponseSet to ResponseInfoBean: "
              + e.getMessage());
    }

    return null; // To change body of implemented methods use File | Settings | File Templates.
  }
コード例 #10
0
ファイル: UserCacheService.java プロジェクト: jongillies/pwm
  public UserCacheRecord updateUserCache(final UserInfoBean userInfoBean)
      throws PwmUnrecoverableException {
    final StorageKey storageKey = StorageKey.fromUserInfoBean(userInfoBean);

    boolean preExisting = false;
    try {
      UserCacheRecord userCacheRecord = readStorageKey(storageKey);
      if (userCacheRecord == null) {
        userCacheRecord = new UserCacheRecord();
      } else {
        preExisting = true;
      }
      userCacheRecord.addUiBeanData(userInfoBean);
      store(userCacheRecord);
      return userCacheRecord;
    } catch (LocalDBException e) {
      LOGGER.error("unable to store user status cache to localdb: " + e.getMessage());
    }
    LOGGER.trace(
        "updateCache: "
            + (preExisting ? "updated existing" : "created new")
            + " user cache for "
            + userInfoBean.getUserIdentity()
            + " user key "
            + storageKey.getKey());
    return null;
  }
コード例 #11
0
ファイル: ConfigGuideServlet.java プロジェクト: aboieriu/pwm
  private void restUpdateLdapForm(
      final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
      throws IOException, PwmUnrecoverableException {
    final StoredConfigurationImpl 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);
        }
      } 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());
  }
コード例 #12
0
  void restUploadWordlist(final PwmRequest pwmRequest)
      throws IOException, ServletException, PwmUnrecoverableException {

    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();

    if (!ServletFileUpload.isMultipartContent(req)) {
      final ErrorInformation errorInformation =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, "no file found in upload");
      pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
      LOGGER.error(pwmRequest, "error during import: " + errorInformation.toDebugStr());
      return;
    }

    final InputStream inputStream =
        ServletHelper.readFileUpload(pwmRequest.getHttpServletRequest(), "uploadFile");
    try {
      pwmApplication.getWordlistManager().populate(inputStream);
    } catch (PwmUnrecoverableException e) {
      final ErrorInformation errorInfo =
          new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
      final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest);
      LOGGER.debug(pwmRequest, errorInfo.toDebugStr());
      pwmRequest.outputJsonResult(restResultBean);
      return;
    }

    pwmRequest.outputJsonResult(
        RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
  }
コード例 #13
0
  public static void saveConfiguration(
      final PwmRequest pwmRequest, final StoredConfigurationImpl storedConfiguration)
      throws PwmUnrecoverableException {
    {
      final List<String> errorStrings = storedConfiguration.validateValues();
      if (errorStrings != null && !errorStrings.isEmpty()) {
        final String errorString = errorStrings.get(0);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
      }
    }

    try {
      ContextManager contextManager =
          ContextManager.getContextManager(
              pwmRequest.getHttpServletRequest().getSession().getServletContext());
      contextManager
          .getConfigReader()
          .saveConfiguration(
              storedConfiguration,
              contextManager.getPwmApplication(),
              pwmRequest.getSessionLabel());
      contextManager.requestPwmApplicationRestart();
    } catch (Exception e) {
      final String errorString = "error saving file: " + e.getMessage();
      LOGGER.error(pwmRequest, errorString);
      throw new PwmUnrecoverableException(
          new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, null, new String[] {errorString}));
    }
  }
コード例 #14
0
ファイル: ReportService.java プロジェクト: jcauthorn/pwm
 private void updateCacheFromLdap()
     throws ChaiUnavailableException, ChaiOperationException, PwmOperationalException,
         PwmUnrecoverableException {
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "beginning process to updating user cache records from ldap");
   if (status != STATUS.OPEN) {
     return;
   }
   cancelFlag = false;
   reportStatus = new ReportStatusInfo(settings.getSettingsHash());
   reportStatus.setInProgress(true);
   reportStatus.setStartDate(new Date());
   try {
     final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers());
     reportStatus.setTotal(allUsers.size());
     while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) {
       final Date startUpdateTime = new Date();
       final UserIdentity userIdentity = allUsers.poll();
       try {
         if (updateCachedRecordFromLdap(userIdentity)) {
           reportStatus.setUpdated(reportStatus.getUpdated() + 1);
         }
       } catch (Exception e) {
         String errorMsg =
             "error while updating report cache for " + userIdentity.toString() + ", cause: ";
         errorMsg +=
             e instanceof PwmException
                 ? ((PwmException) e).getErrorInformation().toDebugStr()
                 : e.getMessage();
         final ErrorInformation errorInformation;
         errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg);
         LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr());
         reportStatus.setLastError(errorInformation);
         reportStatus.setErrors(reportStatus.getErrors() + 1);
       }
       reportStatus.setCount(reportStatus.getCount() + 1);
       reportStatus.getEventRateMeter().markEvents(1);
       final TimeDuration totalUpdateTime = TimeDuration.fromCurrent(startUpdateTime);
       if (settings.isAutoCalcRest()) {
         avgTracker.addSample(totalUpdateTime.getTotalMilliseconds());
         Helper.pause(avgTracker.avgAsLong());
       } else {
         Helper.pause(settings.getRestTime().getTotalMilliseconds());
       }
     }
     if (cancelFlag) {
       reportStatus.setLastError(
           new ErrorInformation(
               PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator"));
     }
   } finally {
     reportStatus.setFinishDate(new Date());
     reportStatus.setInProgress(false);
   }
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "update user cache process completed: " + JsonUtil.serialize(reportStatus));
 }
コード例 #15
0
ファイル: UserCacheService.java プロジェクト: jongillies/pwm
 public ClosableIterator<StorageKey> iterator() {
   try {
     return new UserStatusCacheBeanIterator();
   } catch (LocalDBException e) {
     LOGGER.error("unexpected error generating user status iterator: " + e.getMessage());
     return null;
   }
 }
コード例 #16
0
ファイル: SetupOtpBean.java プロジェクト: idwright/pwm
 public Long getChallenge() {
   if (challenge == null) {
     SecureRandom random;
     try {
       random = SecureRandom.getInstance("SHA1PRNG", "SUN");
     } catch (NoSuchAlgorithmException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     } catch (NoSuchProviderException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     }
     random.setSeed((new Date()).getTime());
     challenge = random.nextLong() % (10 ^ 6);
   }
   return challenge;
 }
コード例 #17
0
 private static void close(final Statement statement) {
   if (statement != null) {
     try {
       statement.close();
     } catch (SQLException e) {
       LOGGER.error("unexpected error during close statement object " + e.getMessage(), e);
     }
   }
 }
コード例 #18
0
ファイル: Statistic.java プロジェクト: pwm-project/pwm
 public String getDescription(final Locale locale) {
   final String keyName = "Statistic_Description." + this.getKey();
   try {
     return LocaleHelper.getLocalizedMessage(locale, keyName, null, Admin.class);
   } catch (Exception e) {
     LOGGER.error("unable to load localization for " + keyName + ", error: " + e.getMessage());
     return "missing localization for " + keyName;
   }
 }
コード例 #19
0
 private static void close(final ResultSet resultSet) {
   if (resultSet != null) {
     try {
       resultSet.close();
     } catch (SQLException e) {
       LOGGER.error("unexpected error during close resultSet object " + e.getMessage(), e);
     }
   }
 }
コード例 #20
0
ファイル: NMASUAWSOperator.java プロジェクト: dragonarmor/pwm
    public boolean test(final Map<Challenge, String> responseTest) throws ChaiUnavailableException {
      if (service == null) {
        LOGGER.error(
            localIdentifier
                + "beginning web service 'processChaRes' response test, however service bean is not in session memory, aborting response test...");
        return false;
      }
      LOGGER.trace(localIdentifier + "beginning web service 'processChaRes' response test ");
      final String[] responseArray = new String[challengeSet.getAdminDefinedChallenges().size()];
      {
        int i = 0;
        for (final Challenge loopChallenge : challengeSet.getAdminDefinedChallenges()) {
          final String loopResponse = responseTest.get(loopChallenge);
          responseArray[i] = loopResponse;
          i++;
        }
      }
      final ProcessChaResRequest request = new ProcessChaResRequest();
      request.setChaAnswers(responseArray);
      request.setUserDN(userDN);

      try {
        final ForgotPasswordWSBean response = service.processChaRes(request);
        if (response.isTimeout()) {
          LOGGER.error(localIdentifier + "web service reports timeout: " + response.getMessage());
          return false;
        }
        if (response.isError()) {
          if ("Account restrictions prevent you from logging in. See your administrator for more details."
              .equals(response.getMessage())) {
            // throw PwmUnrecoverableException.createPwmException(PwmError.ERROR_INTRUDER_USER);
          }
          LOGGER.error(localIdentifier + "web service reports error: " + response.getMessage());
          return false;
        }
        LOGGER.debug(localIdentifier + "web service has validated the users responses");
        return true;
      } catch (RemoteException e) {
        LOGGER.error(localIdentifier + "error processing web service response: " + e.getMessage());
      }

      return false; // To change body of implemented methods use File | Settings | File Templates.
    }
コード例 #21
0
ファイル: StatisticsBundle.java プロジェクト: idwright/pwm
  public synchronized void incrementValue(final Statistic statistic) {
    if (Statistic.Type.INCREMENTOR != statistic.getType()) {
      LOGGER.error("attempt to increment non-counter/incremental stat " + statistic);
      return;
    }

    BigInteger currentValue = BigInteger.ZERO;
    try {
      if (valueMap.containsKey(statistic)) {
        currentValue = new BigInteger(valueMap.get(statistic));
      } else {
        currentValue = BigInteger.ZERO;
      }
    } catch (NumberFormatException e) {
      LOGGER.error("error reading counter/incremental stat " + statistic);
    }
    final BigInteger newValue = currentValue.add(BigInteger.ONE);
    valueMap.put(statistic, newValue.toString());
  }
コード例 #22
0
ファイル: ReportService.java プロジェクト: jcauthorn/pwm
 private void saveTempData() {
   try {
     final String jsonInfo = JsonUtil.serialize(reportStatus);
     pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.REPORT_STATUS, jsonInfo);
   } catch (Exception e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL,
         "error writing cached report dredge info into memory: " + e.getMessage());
   }
 }
コード例 #23
0
  public static Map<String, String> defaultForm(PwmSettingTemplate template) {
    final Map<String, String> defaultLdapForm = new HashMap<>();

    try {
      final String defaultLdapUrlString =
          ((List<String>) PwmSetting.LDAP_SERVER_URLS.getDefaultValue(template).toNativeObject())
              .get(0);
      final URI uri = new URI(defaultLdapUrlString);

      defaultLdapForm.put(PARAM_LDAP_HOST, uri.getHost());
      defaultLdapForm.put(PARAM_LDAP_PORT, String.valueOf(uri.getPort()));
      defaultLdapForm.put(
          PARAM_LDAP_SECURE, "ldaps".equalsIgnoreCase(uri.getScheme()) ? "true" : "false");

      defaultLdapForm.put(
          PARAM_LDAP_ADMIN_DN,
          (String) PwmSetting.LDAP_PROXY_USER_DN.getDefaultValue(template).toNativeObject());
      defaultLdapForm.put(PARAM_LDAP_ADMIN_PW, "");

      defaultLdapForm.put(
          PARAM_LDAP_CONTEXT,
          ((List<String>)
                  PwmSetting.LDAP_CONTEXTLESS_ROOT.getDefaultValue(template).toNativeObject())
              .get(0));
      defaultLdapForm.put(
          PARAM_LDAP_TEST_USER,
          (String) PwmSetting.LDAP_TEST_USER_DN.getDefaultValue(template).toNativeObject());
      {
        List<UserPermission> userPermissions =
            (List<UserPermission>)
                PwmSetting.QUERY_MATCH_PWM_ADMIN.getDefaultValue(template).toNativeObject();
        final String groupDN =
            userPermissions != null && userPermissions.size() > 0
                ? userPermissions.get(0).getLdapBase()
                : "";
        defaultLdapForm.put(PARAM_LDAP_ADMIN_GROUP, groupDN);
      }

      defaultLdapForm.put(
          PARAM_CR_STORAGE_PREF,
          (String)
              PwmSetting.FORGOTTEN_PASSWORD_WRITE_PREFERENCE
                  .getDefaultValue(template)
                  .toNativeObject());

      defaultLdapForm.put(PARAM_CONFIG_PASSWORD, "");
      defaultLdapForm.put(PARAM_CONFIG_PASSWORD_VERIFY, "");
    } catch (Exception e) {
      LOGGER.error(
          "error building static form values using default configuration: " + e.getMessage());
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(defaultLdapForm);
  }
コード例 #24
0
ファイル: RestClientHelper.java プロジェクト: CherifSy/pwm
 public static String makeOutboundRestWSCall(
     final PwmApplication pwmApplication,
     final Locale locale,
     final String url,
     final String jsonRequestBody)
     throws PwmOperationalException, PwmUnrecoverableException {
   final HttpPost httpPost = new HttpPost(url);
   httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue());
   if (locale != null) {
     httpPost.setHeader("Accept-Locale", locale.toString());
   }
   httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue());
   final HttpResponse httpResponse;
   try {
     final StringEntity stringEntity = new StringEntity(jsonRequestBody);
     stringEntity.setContentType(PwmConstants.AcceptValue.json.getHeaderValue());
     httpPost.setEntity(stringEntity);
     LOGGER.debug(
         "beginning external rest call to: " + httpPost.toString() + ", body: " + jsonRequestBody);
     httpResponse = PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost);
     final String responseBody = EntityUtils.toString(httpResponse.getEntity());
     LOGGER.trace(
         "external rest call returned: "
             + httpResponse.getStatusLine().toString()
             + ", body: "
             + responseBody);
     if (httpResponse.getStatusLine().getStatusCode() != 200) {
       final String errorMsg =
           "received non-200 response code ("
               + httpResponse.getStatusLine().getStatusCode()
               + ") when executing web-service";
       LOGGER.error(errorMsg);
       throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
     }
     return responseBody;
   } catch (IOException e) {
     final String errorMsg =
         "http response error while executing external rest call, error: " + e.getMessage();
     LOGGER.error(errorMsg);
     throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg), e);
   }
 }
コード例 #25
0
 protected void handleSelectPageRequest(
     final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean)
     throws PwmUnrecoverableException, IOException, ServletException {
   final String requestedPage = pwmRequest.readParameterAsString("page");
   try {
     guestRegistrationBean.setCurrentPage(Page.valueOf(requestedPage));
   } catch (IllegalArgumentException e) {
     LOGGER.error(pwmRequest, "unknown page select request: " + requestedPage);
   }
   this.forwardToJSP(pwmRequest, guestRegistrationBean);
 }
コード例 #26
0
 public void close() {
   try {
     writeDbValues();
   } catch (Exception e) {
     LOGGER.error("unexpected error closing: " + e.getMessage());
   }
   if (daemonTimer != null) {
     daemonTimer.cancel();
   }
   status = STATUS.CLOSED;
 }
コード例 #27
0
ファイル: ConfigGuideServlet.java プロジェクト: aboieriu/pwm
 private void restExtendSchema(final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
     throws IOException {
   try {
     SchemaOperationResult schemaOperationResult = extendSchema(configGuideBean, true);
     pwmRequest.outputJsonResult(new RestResultBean(schemaOperationResult.getOperationLog()));
   } catch (Exception e) {
     ErrorInformation errorInformation =
         new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
     pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
     LOGGER.error(pwmRequest, e.getMessage(), e);
   }
 }
コード例 #28
0
 public int size() {
   if (localDB != null) {
     try {
       return localDB.size(WORDS_DB);
     } catch (Exception e) {
       LOGGER.error("error checking wordlist size: " + e.getMessage());
       return 0;
     }
   } else {
     return 0;
   }
 }
コード例 #29
0
ファイル: PwmApplication.java プロジェクト: Alqobais/pwm
  public String readAppAttribute(final AppAttribute appAttribute) {
    if (localDB == null || localDB.status() != LocalDB.Status.OPEN) {
      LOGGER.error("error retrieving key '" + appAttribute.getKey() + "', localDB unavailable: ");
      return null;
    }

    if (appAttribute == null) {
      return null;
    }

    try {
      return localDB.get(LocalDB.DB.PWM_META, appAttribute.getKey());
    } catch (Exception e) {
      LOGGER.error(
          "error retrieving key '"
              + appAttribute.getKey()
              + "' installation date from localDB: "
              + e.getMessage());
    }
    return null;
  }
コード例 #30
0
ファイル: ReportService.java プロジェクト: jcauthorn/pwm
  @Override
  public void init(PwmApplication pwmApplication) throws PwmException {
    status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.READ_ONLY) {
      LOGGER.debug(
          PwmConstants.REPORTING_SESSION_LABEL,
          "application mode is read-only, will remain closed");
      status = STATUS.CLOSED;
      return;
    }

    if (pwmApplication.getLocalDB() == null
        || LocalDB.Status.OPEN != pwmApplication.getLocalDB().status()) {
      LOGGER.debug(PwmConstants.REPORTING_SESSION_LABEL, "LocalDB is not open, will remain closed");
      status = STATUS.CLOSED;
      return;
    }

    if (!pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.REPORTING_ENABLE)) {
      LOGGER.debug(
          PwmConstants.REPORTING_SESSION_LABEL,
          "reporting module is not enabled, will remain closed");
      status = STATUS.CLOSED;
      clear();
      return;
    }

    try {
      userCacheService = new UserCacheService();
      userCacheService.init(pwmApplication);
    } catch (Exception e) {
      LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, "unable to init cache service");
      status = STATUS.CLOSED;
      return;
    }

    settings = ReportSettings.readSettingsFromConfig(pwmApplication.getConfig());
    summaryData = ReportSummaryData.newSummaryData(settings.getTrackDays());

    executorService =
        Executors.newSingleThreadScheduledExecutor(
            Helper.makePwmThreadFactory(
                Helper.makeThreadName(pwmApplication, this.getClass()) + "-", true));

    String startupMsg = "report service started";
    LOGGER.debug(startupMsg);

    executorService.submit(new InitializationTask());

    status = STATUS.OPEN;
  }