Search in sources :

Example 66 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PwmApplication method initialize.

private void initialize() throws PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    // initialize log4j
    if (!pwmEnvironment.isInternalRuntimeInstance() && !pwmEnvironment.getFlags().contains(PwmEnvironment.ApplicationFlag.CommandLineInstance)) {
        final String log4jFileName = pwmEnvironment.getConfig().readSettingAsString(PwmSetting.EVENTS_JAVA_LOG4JCONFIG_FILE);
        final File log4jFile = FileSystemUtility.figureFilepath(log4jFileName, pwmEnvironment.getApplicationPath());
        final String consoleLevel;
        final String fileLevel;
        switch(getApplicationMode()) {
            case ERROR:
            case NEW:
                consoleLevel = PwmLogLevel.TRACE.toString();
                fileLevel = PwmLogLevel.TRACE.toString();
                break;
            default:
                consoleLevel = pwmEnvironment.getConfig().readSettingAsString(PwmSetting.EVENTS_JAVA_STDOUT_LEVEL);
                fileLevel = pwmEnvironment.getConfig().readSettingAsString(PwmSetting.EVENTS_FILE_LEVEL);
                break;
        }
        PwmLogManager.initializeLogger(this, pwmEnvironment.getConfig(), log4jFile, consoleLevel, pwmEnvironment.getApplicationPath(), fileLevel);
        switch(getApplicationMode()) {
            case RUNNING:
                break;
            case ERROR:
                LOGGER.fatal("starting up in ERROR mode! Check log or health check information for cause");
                break;
            default:
                LOGGER.trace("setting log level to TRACE because application mode is " + getApplicationMode());
                break;
        }
    }
    // get file lock
    if (!pwmEnvironment.isInternalRuntimeInstance()) {
        pwmEnvironment.waitForFileLock();
    }
    // clear temp dir
    if (!pwmEnvironment.isInternalRuntimeInstance()) {
        final File tempFileDirectory = getTempDirectory();
        try {
            FileSystemUtility.deleteDirectoryContents(tempFileDirectory);
        } catch (Exception e) {
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, "unable to clear temp file directory '" + tempFileDirectory.getAbsolutePath() + "', error: " + e.getMessage()));
        }
    }
    LOGGER.info("initializing, application mode=" + getApplicationMode() + ", applicationPath=" + (pwmEnvironment.getApplicationPath() == null ? "null" : pwmEnvironment.getApplicationPath().getAbsolutePath()) + ", configFile=" + (pwmEnvironment.getConfigurationFile() == null ? "null" : pwmEnvironment.getConfigurationFile().getAbsolutePath()));
    if (!pwmEnvironment.isInternalRuntimeInstance()) {
        if (getApplicationMode() == PwmApplicationMode.ERROR || getApplicationMode() == PwmApplicationMode.NEW) {
            LOGGER.warn("skipping LocalDB open due to application mode " + getApplicationMode());
        } else {
            this.localDB = Initializer.initializeLocalDB(this);
        }
    }
    this.localDBLogger = PwmLogManager.initializeLocalDBLogger(this);
    // log the loaded configuration
    LOGGER.debug("configuration load completed");
    // read the pwm servlet instance id
    instanceID = fetchInstanceID(localDB, this);
    LOGGER.debug("using '" + getInstanceID() + "' for instance's ID (instanceID)");
    // read the pwm installation date
    installTime = fetchInstallDate(startupTime);
    LOGGER.debug("this application instance first installed on " + JavaHelper.toIsoDate(installTime));
    LOGGER.debug("application environment flags: " + JsonUtil.serializeCollection(pwmEnvironment.getFlags()));
    LOGGER.debug("application environment parameters: " + JsonUtil.serializeMap(pwmEnvironment.getParameters()));
    pwmServiceManager.initAllServices();
    final boolean skipPostInit = pwmEnvironment.isInternalRuntimeInstance() || pwmEnvironment.getFlags().contains(PwmEnvironment.ApplicationFlag.CommandLineInstance);
    if (!skipPostInit) {
        final TimeDuration totalTime = TimeDuration.fromCurrent(startTime);
        LOGGER.info(PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION + " open for bidness! (" + totalTime.asCompactString() + ")");
        StatisticsManager.incrementStat(this, Statistic.PWM_STARTUPS);
        LOGGER.debug("buildTime=" + PwmConstants.BUILD_TIME + ", javaLocale=" + Locale.getDefault() + ", DefaultLocale=" + PwmConstants.DEFAULT_LOCALE);
        final Thread postInitThread = new Thread(() -> postInitTasks());
        postInitThread.setDaemon(true);
        postInitThread.setName(JavaHelper.makeThreadName(this, PwmApplication.class));
        postInitThread.start();
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) Instant(java.time.Instant) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) TimeDuration(password.pwm.util.java.TimeDuration) File(java.io.File) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException)

Example 67 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class UserMatchViewerFunction method provideFunction.

@Override
public Serializable provideFunction(final PwmRequest pwmRequest, final StoredConfigurationImpl storedConfiguration, final PwmSetting setting, final String profile, final String extraData) throws Exception {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Date startSearchTime = new Date();
    final int maxResultSize = Integer.parseInt(pwmApplication.getConfig().readAppProperty(AppProperty.CONFIG_EDITOR_QUERY_FILTER_TEST_LIMIT));
    final Collection<UserIdentity> users = discoverMatchingUsers(pwmApplication, maxResultSize, storedConfiguration, setting, profile);
    final TimeDuration searchDuration = TimeDuration.fromCurrent(startSearchTime);
    final UserMatchViewerResults userMatchViewerResults = new UserMatchViewerResults();
    final boolean sizeExceeded = users.size() >= maxResultSize;
    userMatchViewerResults.setUsers(users);
    userMatchViewerResults.setSearchOperationSummary(LocaleHelper.getLocalizedMessage(Display.Display_SearchResultsInfo, pwmRequest, String.valueOf(users.size()), searchDuration.asLongString(pwmRequest.getLocale())));
    userMatchViewerResults.setSizeExceeded(sizeExceeded);
    return userMatchViewerResults;
}
Also used : PwmApplication(password.pwm.PwmApplication) UserIdentity(password.pwm.bean.UserIdentity) TimeDuration(password.pwm.util.java.TimeDuration) Date(java.util.Date)

Example 68 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class ClientApiServlet method makeClientData.

private static Map<String, Object> makeClientData(final PwmApplication pwmApplication, final PwmSession pwmSession, final HttpServletRequest request, final HttpServletResponse response, final String pageUrl) throws ChaiUnavailableException, PwmUnrecoverableException {
    final Locale userLocale = pwmSession.getSessionStateBean().getLocale();
    final Configuration config = pwmApplication.getConfig();
    final TreeMap<String, Object> settingMap = new TreeMap<>();
    settingMap.put("client.ajaxTypingTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_TIMEOUT)));
    settingMap.put("client.ajaxTypingWait", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_WAIT)));
    settingMap.put("client.activityMaxEpsRate", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_ACTIVITY_MAX_EPS_RATE)));
    settingMap.put("client.js.enableHtml5Dialog", Boolean.parseBoolean(config.readAppProperty(AppProperty.CLIENT_JS_ENABLE_HTML5DIALOG)));
    settingMap.put("client.locale", LocaleHelper.getBrowserLocaleString(pwmSession.getSessionStateBean().getLocale()));
    settingMap.put("client.pwShowRevertTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_PW_SHOW_REVERT_TIMEOUT)));
    settingMap.put("enableIdleTimeout", config.readSettingAsBoolean(PwmSetting.DISPLAY_IDLE_TIMEOUT));
    settingMap.put("pageLeaveNotice", config.readSettingAsLong(PwmSetting.SECURITY_PAGE_LEAVE_NOTICE_TIMEOUT));
    settingMap.put("setting-showHidePasswordFields", pwmApplication.getConfig().readSettingAsBoolean(password.pwm.config.PwmSetting.DISPLAY_SHOW_HIDE_PASSWORD_FIELDS));
    settingMap.put("setting-displayEula", PwmConstants.ENABLE_EULA_DISPLAY);
    settingMap.put("setting-showStrengthMeter", config.readSettingAsBoolean(PwmSetting.PASSWORD_SHOW_STRENGTH_METER));
    {
        long idleSeconds = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
        if (pageUrl == null || pageUrl.isEmpty()) {
            LOGGER.warn(pwmSession, "request to /client data did not include pageUrl");
        } else {
            try {
                final PwmURL pwmURL = new PwmURL(new URI(pageUrl), request.getContextPath());
                final TimeDuration maxIdleTime = IdleTimeoutCalculator.idleTimeoutForRequest(pwmURL, pwmApplication, pwmSession);
                idleSeconds = maxIdleTime.getTotalSeconds();
            } catch (Exception e) {
                LOGGER.error(pwmSession, "error determining idle timeout time for request: " + e.getMessage());
            }
        }
        settingMap.put("MaxInactiveInterval", idleSeconds);
    }
    settingMap.put("paramName.locale", config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE));
    settingMap.put("runtimeNonce", pwmApplication.getRuntimeNonce());
    settingMap.put("applicationMode", pwmApplication.getApplicationMode());
    final String contextPath = request.getContextPath();
    settingMap.put("url-context", contextPath);
    settingMap.put("url-logout", contextPath + PwmServletDefinition.Logout.servletUrl());
    settingMap.put("url-command", contextPath + PwmServletDefinition.PublicCommand.servletUrl());
    settingMap.put("url-resources", contextPath + "/public/resources" + pwmApplication.getResourceServletService().getResourceNonce());
    settingMap.put("url-restservice", contextPath + "/public/rest");
    {
        String passwordGuideText = pwmApplication.getConfig().readSettingAsLocalizedString(PwmSetting.DISPLAY_PASSWORD_GUIDE_TEXT, pwmSession.getSessionStateBean().getLocale());
        final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication);
        passwordGuideText = macroMachine.expandMacros(passwordGuideText);
        settingMap.put("passwordGuideText", passwordGuideText);
    }
    {
        final List<String> formTypeOptions = new ArrayList<>();
        for (final FormConfiguration.Type type : FormConfiguration.Type.values()) {
            formTypeOptions.add(type.toString());
        }
        settingMap.put("formTypeOptions", formTypeOptions);
    }
    {
        final List<String> actionTypeOptions = new ArrayList<>();
        for (final ActionConfiguration.Type type : ActionConfiguration.Type.values()) {
            actionTypeOptions.add(type.toString());
        }
        settingMap.put("actionTypeOptions", actionTypeOptions);
    }
    {
        final List<String> epsTypes = new ArrayList<>();
        for (final EpsStatistic loopEpsType : EpsStatistic.values()) {
            epsTypes.add(loopEpsType.toString());
        }
        settingMap.put("epsTypes", epsTypes);
    }
    {
        final List<String> epsDurations = new ArrayList<>();
        for (final Statistic.EpsDuration loopEpsDuration : Statistic.EpsDuration.values()) {
            epsDurations.add(loopEpsDuration.toString());
        }
        settingMap.put("epsDurations", epsDurations);
    }
    {
        final Map<String, String> localeInfo = new LinkedHashMap<>();
        final Map<String, String> localeDisplayNames = new LinkedHashMap<>();
        final Map<String, String> localeFlags = new LinkedHashMap<>();
        final List<Locale> knownLocales = new ArrayList<>(pwmApplication.getConfig().getKnownLocales());
        knownLocales.sort(LocaleHelper.localeComparator(PwmConstants.DEFAULT_LOCALE));
        for (final Locale locale : knownLocales) {
            final String flagCode = pwmApplication.getConfig().getKnownLocaleFlagMap().get(locale);
            localeFlags.put(locale.toString(), flagCode);
            localeInfo.put(locale.toString(), locale.getDisplayName(PwmConstants.DEFAULT_LOCALE) + " - " + locale.getDisplayLanguage(userLocale));
            localeDisplayNames.put(locale.toString(), locale.getDisplayLanguage());
        }
        settingMap.put("localeInfo", localeInfo);
        settingMap.put("localeDisplayNames", localeDisplayNames);
        settingMap.put("localeFlags", localeFlags);
        settingMap.put("defaultLocale", PwmConstants.DEFAULT_LOCALE.toString());
    }
    if (pwmApplication.getConfig().readSettingAsEnum(PwmSetting.LDAP_SELECTABLE_CONTEXT_MODE, SelectableContextMode.class) != SelectableContextMode.NONE) {
        final Map<String, Map<String, String>> ldapProfiles = new LinkedHashMap<>();
        for (final String ldapProfile : pwmApplication.getConfig().getLdapProfiles().keySet()) {
            final Map<String, String> contexts = pwmApplication.getConfig().getLdapProfiles().get(ldapProfile).getSelectableContexts(pwmApplication);
            ldapProfiles.put(ldapProfile, contexts);
        }
        settingMap.put("ldapProfiles", ldapProfiles);
    }
    return settingMap;
}
Also used : Locale(java.util.Locale) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ActionConfiguration(password.pwm.config.value.data.ActionConfiguration) Configuration(password.pwm.config.Configuration) PwmURL(password.pwm.http.PwmURL) SelectableContextMode(password.pwm.config.option.SelectableContextMode) TreeMap(java.util.TreeMap) URI(java.net.URI) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) MacroMachine(password.pwm.util.macro.MacroMachine) TimeDuration(password.pwm.util.java.TimeDuration) List(java.util.List) ArrayList(java.util.ArrayList) EpsStatistic(password.pwm.svc.stats.EpsStatistic) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 69 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class ConfigAccessFilter method forwardToJsp.

private static void forwardToJsp(final PwmRequest pwmRequest) throws ServletException, PwmUnrecoverableException, IOException {
    final int persistentSeconds = figureMaxLoginSeconds(pwmRequest);
    final String time = new TimeDuration(persistentSeconds * 1000).asLongString(pwmRequest.getLocale());
    final ConfigLoginHistory configLoginHistory = readConfigLoginHistory(pwmRequest);
    pwmRequest.setAttribute(PwmRequestAttribute.ConfigLoginHistory, configLoginHistory);
    pwmRequest.setAttribute(PwmRequestAttribute.ConfigPasswordRememberTime, time);
    pwmRequest.forwardToJsp(JspUrl.CONFIG_MANAGER_LOGIN);
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration)

Example 70 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PwmHttpClient method makeRequestImpl.

private PwmHttpClientResponse makeRequestImpl(final PwmHttpClientRequest clientRequest) throws IOException, URISyntaxException, PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    final int counter = classCounter++;
    LOGGER.trace(sessionLabel, "preparing to send (id=" + counter + ") " + clientRequest.toDebugString(this));
    final HttpResponse httpResponse = executeRequest(clientRequest);
    final String responseBody = EntityUtils.toString(httpResponse.getEntity());
    final Map<String, String> responseHeaders = new LinkedHashMap<>();
    if (httpResponse.getAllHeaders() != null) {
        for (final Header header : httpResponse.getAllHeaders()) {
            responseHeaders.put(header.getName(), header.getValue());
        }
    }
    final PwmHttpClientResponse httpClientResponse = new PwmHttpClientResponse(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), responseHeaders, responseBody);
    final TimeDuration duration = TimeDuration.fromCurrent(startTime);
    LOGGER.trace(sessionLabel, "received response (id=" + counter + ") in " + duration.asCompactString() + ": " + httpClientResponse.toDebugString(this));
    return httpClientResponse;
}
Also used : Header(org.apache.http.Header) HttpHeader(password.pwm.http.HttpHeader) Instant(java.time.Instant) HttpResponse(org.apache.http.HttpResponse) TimeDuration(password.pwm.util.java.TimeDuration) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

TimeDuration (password.pwm.util.java.TimeDuration)75 Instant (java.time.Instant)28 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)19 PwmException (password.pwm.error.PwmException)14 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 IOException (java.io.IOException)9 Configuration (password.pwm.config.Configuration)8 PwmOperationalException (password.pwm.error.PwmOperationalException)8 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)7 Map (java.util.Map)7 UserIdentity (password.pwm.bean.UserIdentity)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)6 MacroMachine (password.pwm.util.macro.MacroMachine)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Locale (java.util.Locale)5