List of usage examples for org.apache.commons.lang.time DateUtils MILLIS_PER_MINUTE
long MILLIS_PER_MINUTE
To view the source code for org.apache.commons.lang.time DateUtils MILLIS_PER_MINUTE.
Click Source Link
From source file:org.apache.eagle.jobrunning.crawler.RunningJobCrawlerImpl.java
public void startCompleteStatusCheckerThread() { while (true) { List<Object> list; try {//from w ww . j a v a 2s . c o m list = fetcher.getResource(ResourceType.JOB_LIST, JobState.COMPLETED.name()); if (list == null) { LOG.warn("Current Completed Job List is Empty"); continue; } @SuppressWarnings("unchecked") List<AppInfo> apps = (List<AppInfo>) list.get(0); Set<JobContext> completedJobSet = new HashSet<JobContext>(); for (AppInfo app : apps) { //Only fetch MapReduce job if (!YarnApplicationType.MAPREDUCE.name().equals(app.getApplicationType()) || !jobFilter.accept(app.getUser())) { continue; } if (System.currentTimeMillis() - app.getFinishedTime() < controlConfig.completedJobOutofDateTimeInMin * DateUtils.MILLIS_PER_MINUTE) { completedJobSet.add(new JobContext(JobUtils.getJobIDByAppID(app.getId()), app.getUser(), System.currentTimeMillis())); } } if (controlConfig.jobConfigEnabled) { addIntoProcessingQueueAndList(completedJobSet, queueOfConfig, ResourceType.JOB_CONFIGURATION); } if (controlConfig.jobInfoEnabled) { addIntoProcessingQueueAndList(completedJobSet, queueOfCompleteJobInfo, ResourceType.JOB_COMPLETE_INFO); } Thread.sleep(20 * 1000); } catch (Throwable t) { LOG.error("Got a throwable in fetching job completed list :", t); } } }
From source file:org.apache.eagle.metric.kafka.KafkaMessageDistributionBolt.java
@Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { String site = config.getString("dataSourceConfig.site"); String topic = config.getString("dataSourceConfig.topic"); this.baseMetricDimension = new HashMap<>(); this.baseMetricDimension.put("site", site); this.baseMetricDimension.put("topic", topic); registry = new MetricRegistry(); this.granularity = DEFAULT_METRIC_GRANULARITY; if (config.hasPath("dataSourceConfig.kafkaDistributionDataIntervalMin")) { this.granularity = config.getInt("dataSourceConfig.kafkaDistributionDataIntervalMin") * DateUtils.MILLIS_PER_MINUTE; }/*from ww w. j a va2 s . c o m*/ String host = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.HOST); int port = config.getInt(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PORT); String username = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME); String password = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD); listener = new EagleServiceReporterMetricListener(host, port, username, password); }
From source file:org.apache.eagle.metric.kafka.KafkaMessageDistributionExecutor.java
@Override public void init() { String site = config.getString("dataSourceConfig.site"); String topic = config.getString("dataSourceConfig.topic"); this.baseMetricDimension = new HashMap<>(); this.baseMetricDimension.put("site", site); this.baseMetricDimension.put("topic", topic); registry = new MetricRegistry(); this.granularity = DEFAULT_METRIC_GRANULARITY; if (config.hasPath("dataSourceConfig.kafkaDistributionDataIntervalMin")) { this.granularity = config.getInt("dataSourceConfig.kafkaDistributionDataIntervalMin") * DateUtils.MILLIS_PER_MINUTE; }//from w w w. j a va2 s.com String host = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.HOST); int port = config.getInt(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PORT); String username = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME); String password = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD); listener = new EagleServiceReporterMetricListener(host, port, username, password); }
From source file:org.apache.eagle.metric.reportor.EagleMetric.java
public EagleMetric(long latestUserTimeClock, String metricName, double value) { this(latestUserTimeClock, metricName, value, 5 * DateUtils.MILLIS_PER_MINUTE); }
From source file:org.cloudifysource.shell.commands.InstallService.java
@Override public Object doExecuteNewRestClient() throws Exception { RestClient newRestClient = ((RestAdminFacade) getRestAdminFacade()).getNewRestClient(); NameAndPackedFileResolver nameAndPackedFileResolver = getResolver(recipe); serviceName = nameAndPackedFileResolver.getName(); File packedFile = nameAndPackedFileResolver.getPackedFile(); // upload the files if necessary final String cloudConfigurationFileKey = ShellUtils.uploadToRepo(newRestClient, cloudConfiguration, displayer);/* w w w . j a va2 s.co m*/ final String cloudOverridesFileKey = ShellUtils.uploadToRepo(newRestClient, cloudOverrides, displayer); final String overridesFileKey = ShellUtils.uploadToRepo(newRestClient, overrides, displayer); final String recipeFileKey = ShellUtils.uploadToRepo(newRestClient, packedFile, displayer); InstallServiceRequest request = new InstallServiceRequest(); request.setAuthGroups(authGroups); request.setCloudConfigurationUploadKey(cloudConfigurationFileKey); request.setDebugAll(debugAll); request.setCloudOverridesUploadKey(cloudOverridesFileKey); request.setDebugEvents(debugEvents); request.setServiceOverridesUploadKey(overridesFileKey); request.setServiceFolderUploadKey(recipeFileKey); request.setSelfHealing(disableSelfHealing); request.setTimeoutInMillis(timeoutInMinutes * DateUtils.MILLIS_PER_MINUTE); // execute the request InstallServiceResponse installServiceResponse = newRestClient.installService(getCurrentApplicationName(), serviceName, request); CLIServiceInstaller installer = new CLIServiceInstaller(); installer.setApplicationName(getCurrentApplicationName()); installer.setAskOnTimeout(true); installer.setDeploymentId(installServiceResponse.getDeploymentID()); installer.setInitialTimeout(timeoutInMinutes); installer.setRestClient(newRestClient); installer.setServiceName(serviceName); installer.setSession(session); installer.setPlannedNumberOfInstances( nameAndPackedFileResolver.getPlannedNumberOfInstancesPerService().get(serviceName)); installer.install(); return getFormattedMessage("service_install_ended", Color.GREEN, serviceName); }
From source file:org.jumpmind.symmetric.service.impl.PurgeService.java
private int purgeByMinMax(long[] minMax, MinMaxDeleteSql identifier, Date retentionTime, int maxNumtoPurgeinTx) { long minId = minMax[0]; long purgeUpToId = minMax[1]; long ts = System.currentTimeMillis(); int totalCount = 0; int totalDeleteStmts = 0; int idSqlType = symmetricDialect.getSqlTypeForIds(); Timestamp cutoffTime = new Timestamp(retentionTime.getTime()); log.info("About to purge {}", identifier.toString().toLowerCase()); while (minId <= purgeUpToId) { totalDeleteStmts++;/*from w ww . j a va 2 s . c om*/ long maxId = minId + maxNumtoPurgeinTx; if (maxId > purgeUpToId) { maxId = purgeUpToId; } String deleteSql = null; Object[] args = null; int[] argTypes = null; switch (identifier) { case DATA: deleteSql = getSql("deleteDataSql"); args = new Object[] { minId, maxId, cutoffTime, minId, maxId, minId, maxId, OutgoingBatch.Status.OK.name() }; argTypes = new int[] { idSqlType, idSqlType, Types.TIMESTAMP, idSqlType, idSqlType, idSqlType, idSqlType, Types.VARCHAR }; break; case DATA_EVENT: deleteSql = getSql("deleteDataEventSql"); args = new Object[] { minId, maxId, OutgoingBatch.Status.OK.name(), minId, maxId }; argTypes = new int[] { idSqlType, idSqlType, Types.VARCHAR, idSqlType, idSqlType }; break; case OUTGOING_BATCH: deleteSql = getSql("deleteOutgoingBatchSql"); args = new Object[] { OutgoingBatch.Status.OK.name(), minId, maxId, minId, maxId }; argTypes = new int[] { Types.VARCHAR, idSqlType, idSqlType, idSqlType, idSqlType }; break; case STRANDED_DATA: deleteSql = getSql("deleteStrandedData"); args = new Object[] { minId, maxId, cutoffTime, minId, maxId }; argTypes = new int[] { idSqlType, idSqlType, Types.TIMESTAMP, idSqlType, idSqlType }; break; } log.debug("Running the following statement: {} with the following arguments: {}", deleteSql, Arrays.toString(args)); int count = sqlTemplate.update(deleteSql, args, argTypes); log.debug("Deleted {} rows", count); totalCount += count; if (totalCount > 0 && (System.currentTimeMillis() - ts > DateUtils.MILLIS_PER_MINUTE * 5)) { log.info("Purged {} of {} rows so far using {} statements", new Object[] { totalCount, identifier.toString().toLowerCase(), totalDeleteStmts }); ts = System.currentTimeMillis(); } minId = maxId + 1; } log.info("Done purging {} of {} rows", totalCount, identifier.toString().toLowerCase()); return totalCount; }
From source file:org.jumpmind.symmetric.service.impl.PurgeService.java
private int purgeByNodeBatchRangeList(List<NodeBatchRange> nodeBatchRangeList) { long ts = System.currentTimeMillis(); int totalCount = 0; int totalDeleteStmts = 0; log.info("About to purge incoming batch"); for (NodeBatchRange nodeBatchRange : nodeBatchRangeList) { int maxNumOfDataIdsToPurgeInTx = parameterService .getInt(ParameterConstants.PURGE_MAX_NUMBER_OF_BATCH_IDS); long minBatchId = nodeBatchRange.getMinBatchId(); long purgeUpToBatchId = nodeBatchRange.getMaxBatchId(); while (minBatchId <= purgeUpToBatchId) { totalDeleteStmts++;/*from w w w .j a v a 2s . c o m*/ long maxBatchId = minBatchId + maxNumOfDataIdsToPurgeInTx; if (maxBatchId > purgeUpToBatchId) { maxBatchId = purgeUpToBatchId; } totalCount += sqlTemplate.update(getSql("deleteIncomingBatchSql"), new Object[] { minBatchId, maxBatchId, nodeBatchRange.getNodeId(), IncomingBatch.Status.OK.name() }); minBatchId = maxBatchId + 1; } if (totalCount > 0 && (System.currentTimeMillis() - ts > DateUtils.MILLIS_PER_MINUTE * 5)) { log.info("Purged {} incoming batch rows so far using {} statements", new Object[] { totalCount, totalDeleteStmts }); ts = System.currentTimeMillis(); } } log.info("Done purging {} incoming batch rows", totalCount); return totalCount; }
From source file:org.openanzo.servlet.EncryptedTokenAuthenticator.java
/** * Perform form authentication. Called from SecurityHandler. * //w ww . j a v a2s . c o m * @param servletRequest * request to authenticate * @param response * response to send response data * * @return UserPrincipal if authenticated else null. * @throws IOException */ @SuppressWarnings("null") public boolean authenticate(HttpServletRequest servletRequest, HttpServletResponse response) throws IOException { // NOTE: Jetty will sometimes call this method with a null response parameter. In particular, from // the org.eclipse.jetty.Request#getUserPrincipal() method. boolean ret = false; Request request = Request.getRequest(servletRequest); String uri = request.getServletPath(); boolean protectedPath = false; for (PathSpec spec : protectedPathSpec) { if (spec.matches(uri)) { protectedPath = true; break; } } // Setup some defaults. Unfortunately, this is the only place we really get to set these up since the // Authenticator interface doesn't have an 'init'-like method. if (tokenTimeout <= 0) { tokenTimeout = 30 * DateUtils.MILLIS_PER_MINUTE; } if (tokenRefreshWindow <= 0) { tokenRefreshWindow = 5 * DateUtils.MILLIS_PER_MINUTE; } if (customTokenRefresh == null) { customTokenRefresh = Boolean.FALSE; } // Now handle the request uri = request.getPathInfo(); if (uri.endsWith(LOGIN_URI_SUFFIX)) { // Handle a request for authentication. ret = false; // We will entirely handle the request here so return false to stop processing the request. String username = request.getParameter(USERNAME_PARAMETER_NAME); String password = request.getParameter(PASSWORD_PARAMETER_NAME); if (username == null || password == null) { log.error(LogUtils.SECURITY_MARKER, "Invalid anzo_authenticate request url:{} username:{} password:{}", new Object[] { uri, username, password == null ? null : "XXXObscuredNonNullPasswordXXX" }); } AnzoPrincipal userPrincipal = null; try { userPrincipal = realm.authenticate(username, password, request); } catch (Exception e) { // No matter what sort of failure occurs in the realm we want to make sure to send the appropriate // error response or redirect. So we can't all exceptions here. log.debug(LogUtils.SECURITY_MARKER, "Failed authentication call to the realm.", e); } if (userPrincipal == null) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Authentication request FAILED for {}", StringUtil.printable(username)); } request.setAuthentication(null); if (response != null) { if (_formErrorPage == null || isRequestSentByXmlHttpRequest(request)) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Sending 403 Forbidden error due to invalid credentials for user {}", username); } response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { String redirectPath = response .encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form error page {}", redirectPath); response.setContentLength(0); response.sendRedirect(redirectPath); } } } else { // Authenticated OK if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Authentication request OK for {}", StringUtil.printable(username)); } request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD)); // Set the encrypted token if (response != null) { try { String token = createEncryptedToken(username, request.getRemoteAddr()); Cookie tokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, token); tokenCookie.setPath("/"); response.addCookie(tokenCookie); if (isRequestSentByXmlHttpRequest(request)) { // XMLHttpRequests just want a response with the cookie, no fancy redirects or anything like that. // just send back 200 in text.(Need to send back something else firefox reports an error) response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.print(HttpServletResponse.SC_OK); out.flush(); out.close(); } else { // Redirect to the URL to user wanted to get to initially, or "/" if there isn't any such URL. // We get the URL from a query parameter in the HTTP Referer (sic) header. String referer = request.getHeader(HttpHeaders.REFERER); String redirectPath = null; if (referer != null) { HttpURI refererUri = new HttpURI(referer); MultiMap<String> queryParams = new MultiMap<String>(); refererUri.decodeQueryTo(queryParams, null); String desiredUrl = (String) queryParams.getValue(ANZO_URL_QUERY_PARAM, 0); if (desiredUrl != null) { redirectPath = desiredUrl; } } if (redirectPath == null) { redirectPath = URIUtil.addPaths(request.getContextPath(), "/"); } redirectPath = response.encodeRedirectURL(redirectPath); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to root {} after successful login request.", redirectPath); response.sendRedirect(redirectPath); } } catch (AnzoException cause) { IOException ex = new IOException("Error creating encrypted authentication token."); ex.initCause(cause); throw ex; } } } } else if (isLoginOrErrorPage(uri)) { // Don't authenticate authform or errorpage. Just let the system them out. ret = true; } else if (protectedPath) { // This is a regular request for a protected resource, so check whether there is a valid // encrypted token in the request. AnzoPrincipal userPrincipal = null; // Parse and validate the authentication token from the cookie Token token = null; long currentTime = System.currentTimeMillis(); Cookie[] cookies = request.getCookies(); Cookie tokenCookie = null; if (cookies != null) { for (Cookie cookie : cookies) { String cookieName = cookie.getName(); if (ANZO_TOKEN_COOKIE_NAME.equals(cookieName)) { tokenCookie = cookie; try { token = parseAnzoToken(cookie.getValue()); userPrincipal = validateAuthToken(token, realm, request.getRemoteAddr(), currentTime); } catch (AnzoException e) { log.debug(LogUtils.SECURITY_MARKER, "Error decrypting and parsing authentication token.", e); } break; } } } if (userPrincipal == null) { // Invalid, expired, or non-existent token ret = false; // Don't serve the resource if (log.isDebugEnabled()) { String msg = "Auth token "; if (tokenCookie == null) { msg += "MISSING"; } else { msg += "INVALID"; } log.debug(LogUtils.SECURITY_MARKER, msg + " for URL: {}", StringUtil.printable(request.getRequestURI())); } if (response != null) { Cookie cookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, ""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); // adding a cookie with MaxAge=0 tells the client to delete the cookie. if (_formLoginPage == null || isRequestSentByXmlHttpRequest(request)) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Sending 403 Forbidden error due to invalid auth token. Token: {}", token); } response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // We save the URL the user tried to access into a query parameter in the redirect to the login page. // That way the login page can send the user to the page they wanted after they finish logging in. // First we must reconstruct the URL the user accessed. String requestUrl = uri; if (request.getQueryString() != null) { requestUrl += "?" + request.getQueryString(); } requestUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URIUtil.addPaths(request.getContextPath(), requestUrl); // Now we add the requested URL as a query parameter to the login URL MultiMap<String> loginPageUrlQueryParams = new MultiMap<String>(); loginPageUrlQueryParams.put(ANZO_URL_QUERY_PARAM, requestUrl); String loginPageUrl = URIUtil.addPaths(request.getContextPath(), _formLoginPage); try { loginPageUrl = addQueryParametersToURI(loginPageUrl, loginPageUrlQueryParams); } catch (URISyntaxException e) { log.warn(LogUtils.SECURITY_MARKER, "Error creating login redirect URL. The user's attempted URL won't be saved for use after login.", e); } String redirectPath = response.encodeRedirectURL(loginPageUrl); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form login page {} after request without adequate credentials.", redirectPath); response.setContentLength(0); response.sendRedirect(redirectPath); } } } else { // Properly authenticated if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Auth token OK for '{}' for URL:{}", StringUtil.printable(userPrincipal.getName()), StringUtil.printable(request.getRequestURI())); } if (userPrincipal instanceof AnzoPrincipal) { request.setAttribute(SerializationConstants.authenticationURI, (userPrincipal).getUserURI()); } request.setAttribute(SerializationConstants.userPrincipal, userPrincipal); request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD)); ret = true; // Check if the token is older than the refresh window. If so, create a new cookie with an updated timestamp. try { if (currentTime < token.getTimestamp() || (currentTime - token.getTimestamp() >= tokenRefreshWindow)) { // if current time is less than the token's time, we'll issue a new cookie. That should only ever happen upon overflow of the number of milliseconds from the epoch. String cookieval = createEncryptedToken(token.getUsername(), token.getRemoteAddress()); Cookie newTokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, cookieval); newTokenCookie.setPath("/"); if (customTokenRefresh) { request.setAttribute(ANZO_REFRESH_COOKIE_ATTRIBUTE, newTokenCookie); } else { response.addCookie(newTokenCookie); } } } catch (AnzoException e) { log.error(LogUtils.SECURITY_MARKER, "Could NOT update timestamp on authentication token. Authentication session may end prematurely.", e); } } } else { // This is NOT a protected resource so just let it be served. ret = true; } log.debug(LogUtils.SECURITY_MARKER, "Returning from 'authenticate' with {} for path {}", ret, uri); return ret; }
From source file:org.openvpms.archetype.rules.workflow.FreeSlotQuery.java
/** * Sets the minimum slot size./*from w w w. j a v a 2s . c om*/ * * @param size the size, or {@code 0} to include all slots * @param units the size units */ public void setMinSlotSize(int size, DateUnits units) { switch (units) { case WEEKS: minSlotSize = size * DateUtils.MILLIS_PER_DAY * 7; break; case DAYS: minSlotSize = size * DateUtils.MILLIS_PER_DAY; break; case HOURS: minSlotSize = size * DateUtils.MILLIS_PER_HOUR; break; case MINUTES: minSlotSize = size * DateUtils.MILLIS_PER_MINUTE; break; default: minSlotSize = 0; } }
From source file:org.openvpms.web.echo.servlet.SessionMonitor.java
/** * Constructs an {@link SessionMonitor}. *//*from w ww .j a v a 2 s .c om*/ public SessionMonitor() { executor = Executors.newSingleThreadScheduledExecutor(); log.info("Using default session auto-lock time=" + (autoLock / DateUtils.MILLIS_PER_MINUTE) + " minutes"); log.info("Using default session auto-logout time=" + (autoLogout / DateUtils.MILLIS_PER_MINUTE) + " minutes"); }