List of usage examples for org.joda.time DateTime minusMinutes
public DateTime minusMinutes(int minutes)
From source file:org.graylog2.alerts.StaticEmailAlertSender.java
License:Open Source License
protected String buildStreamDetailsURL(URI baseUri, AlertCondition.CheckResult checkResult, Stream stream) { // Return an empty string if the transport_email_web_interface_url setting has not been set in the config. if (baseUri == null) { return ""; }/*from w w w. j a va 2 s .co m*/ StringBuilder sb = new StringBuilder(); int time = 5; if (checkResult.getTriggeredCondition().getParameters().get("time") != null) time = (int) checkResult.getTriggeredCondition().getParameters().get("time"); DateTime dateAlertEnd = checkResult.getTriggeredAt(); DateTime dateAlertStart = dateAlertEnd.minusMinutes(time); String alertStart = Tools.getISO8601String(dateAlertStart); String alertEnd = Tools.getISO8601String(dateAlertEnd); sb.append(baseUri).append("/streams/").append(stream.getId()).append("/messages"); sb.append("?rangetype=absolute&from=").append(alertStart).append("&to=").append(alertEnd).append("&q=*\n"); return sb.toString(); }
From source file:org.graylog2.periodical.TrafficCounterCalculator.java
License:Open Source License
@Override public void doRun() { final DateTime now = Tools.nowUTC(); final int secondOfMinute = now.getSecondOfMinute(); // on the top of every minute, we flush the current throughput if (secondOfMinute == 0) { LOG.trace("Calculating input and output traffic for the previous minute"); final long currentInputBytes = inputCounter.getCount(); final long currentOutputBytes = outputCounter.getCount(); final long currentDecodedBytes = decodedCounter.getCount(); final long inputLastMinute = currentInputBytes - previousInputBytes; previousInputBytes = currentInputBytes; final long outputBytesLastMinute = currentOutputBytes - previousOutputBytes; previousOutputBytes = currentOutputBytes; final long decodedBytesLastMinute = currentDecodedBytes - previousDecodedBytes; previousDecodedBytes = currentDecodedBytes; if (LOG.isDebugEnabled()) { final Size in = Size.bytes(inputLastMinute); final Size out = Size.bytes(outputBytesLastMinute); final Size decoded = Size.bytes(decodedBytesLastMinute); LOG.debug(/* w w w. j a v a 2 s. c om*/ "Traffic in the last minute: in: {} bytes ({} MB), out: {} bytes ({} MB}), decoded: {} bytes ({} MB})", in, in.toMegabytes(), out, out.toMegabytes(), decoded, decoded.toMegabytes()); } final DateTime previousMinute = now.minusMinutes(1); trafficService.updateTraffic(previousMinute, nodeId, inputLastMinute, outputBytesLastMinute, decodedBytesLastMinute); } }
From source file:org.hawkular.metrics.core.impl.CreateTenants.java
License:Apache License
private long getBucket(Trigger trigger) { DateTime end = new DateTime(trigger.getTriggerTime()); return end.minusMinutes(30).getMillis(); }
From source file:org.medici.bia.common.search.UserSearch.java
License:Open Source License
/** * {@inheritDoc}//from w w w .j ava 2 s .c o m */ @Override public String toJPAQuery() { StringBuilder jpaQuery = new StringBuilder("FROM User "); if (!empty()) { jpaQuery.append("WHERE "); if (getOnline() != null) { DateTime dateTime = new DateTime(System.currentTimeMillis()); dateTime = dateTime.minusMinutes(5); jpaQuery.append(" (dateAndTime > '"); jpaQuery.append(DateUtils.getMYSQLDateTime(dateTime)); jpaQuery.append("')"); } } return jpaQuery.toString(); }
From source file:org.ohmage.request.event.EventReadRequest.java
License:Apache License
/** * Creates an Event read request.//w w w .ja v a 2 s . c o m * * @param httpRequest The HttpServletRequest with the parameters for this * request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public EventReadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, null); LOGGER.info("Creating an Event read request."); String tUsername = null; DateTime tStartDate = null; StreamReadRequest tRegularReadRequest = null; StreamReadRequest tExtendedReadRequest = null; Collection<ColumnKey> tColumns = null; if (!isFailed()) { try { String[] t; getParameters().keySet().size(); t = getParameterValues(InputKeys.DATE); if (t.length == 0) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "The date value is missing: " + InputKeys.DATE); } else if (t.length == 1) { tStartDate = MobilityValidators.validateDate(t[0]); if (tStartDate == null) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "The date value is missing: " + InputKeys.DATE); } else { tStartDate = new DateTime(tStartDate.getYear(), tStartDate.getMonthOfYear(), tStartDate.getDayOfMonth(), 0, 0, DateTimeZone.UTC); } } else { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "Multiple date values were given: " + InputKeys.DATE); } // tColumns = null; // // // t = getParameterValues(InputKeys.MOBILITY_WITH_SENSOR_DATA); // if(t.length > 1) { // throw new ValidationException( // ErrorCode.MOBILITY_INVALID_INCLUDE_SENSOR_DATA_VALUE, // "Multiple \"include sensor data\" values to query were given: " + // InputKeys.MOBILITY_WITH_SENSOR_DATA); // } // else if(t.length == 1) { // if(MobilityValidators.validateIncludeSensorDataValue(t[0])) { // tColumns = MobilityColumnKey.ALL_COLUMNS; // } // } // // t = getParameterValues(InputKeys.COLUMN_LIST); // if(t.length > 1) { // throw new ValidationException( // ErrorCode.MOBILITY_INVALID_COLUMN_LIST, // "Multiple column lists were given: " + // InputKeys.COLUMN_LIST); // } // else if(t.length == 1) { // if(! StringUtils.isEmptyOrWhitespaceOnly(t[0])) { // if(tColumns == null) { // tColumns = // MobilityValidators.validateColumns( // t[0], // true); // } // else { // throw new ValidationException( // ErrorCode.MOBILITY_INVALID_COLUMN_LIST, // "Both '" + // InputKeys.MOBILITY_WITH_SENSOR_DATA + // "' and '" + // InputKeys.COLUMN_LIST + // "' were present. Only one may be present."); // } // } // } // if(tColumns == null) { // tColumns = DEFAULT_COLUMNS; // } // Get the user. t = getParameterValues(InputKeys.USERNAME); if (t.length > 1) { throw new ValidationException(ErrorCode.USER_INVALID_USERNAME, "Multiple usernames to query were given: " + InputKeys.USERNAME); } else if (t.length == 1) { tUsername = UserValidators.validateUsername(t[0]); } // TODO forget all that stream nonsense, just call .NET from here // Always get all of the columns. try { tRegularReadRequest = new StreamReadRequest(httpRequest, getParameterMap(), false, TokenLocation.EITHER, false, tUsername, "edu.ucla.cens.Mobility", null, "regular", 2012050700, tStartDate.minusMinutes(10), tStartDate.plusDays(1), null, true, null, null); tExtendedReadRequest = new StreamReadRequest(httpRequest, getParameterMap(), false, TokenLocation.EITHER, false, tUsername, "edu.ucla.cens.Mobility", null, "extended", 2012050700, tStartDate.minusMinutes(10), tStartDate.plusDays(1), null, true, null, null); } catch (IllegalArgumentException e) { throw new ValidationException("There was an error creating the request.", e); } } catch (ValidationException e) { e.failRequest(this); e.logException(LOGGER); } } username = tUsername; startDate = tStartDate; regularReadRequest = tRegularReadRequest; extendedReadRequest = tExtendedReadRequest; columns = tColumns; points = new ArrayList<MobilityPoint>(); }
From source file:org.ohmage.request.mobility.MobilityReadRequest.java
License:Apache License
/** * Creates a Mobility read request.// w ww .ja va2 s . c om * * @param httpRequest The HttpServletRequest with the parameters for this * request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public MobilityReadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, null); LOGGER.info("Creating a Mobility read request."); String tUsername = null; DateTime tStartDate = null; StreamReadRequest tRegularReadRequest = null; StreamReadRequest tExtendedReadRequest = null; Collection<ColumnKey> tColumns = null; if (!isFailed()) { try { String[] t; t = getParameterValues(InputKeys.DATE); if (t.length == 0) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "The date value is missing: " + InputKeys.DATE); } else if (t.length == 1) { tStartDate = MobilityValidators.validateDate(t[0]); if (tStartDate == null) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "The date value is missing: " + InputKeys.DATE); } else { tStartDate = new DateTime(tStartDate.getYear(), tStartDate.getMonthOfYear(), tStartDate.getDayOfMonth(), 0, 0, DateTimeZone.UTC); } } else { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, "Multiple date values were given: " + InputKeys.DATE); } tColumns = null; t = getParameterValues(InputKeys.MOBILITY_WITH_SENSOR_DATA); if (t.length > 1) { throw new ValidationException(ErrorCode.MOBILITY_INVALID_INCLUDE_SENSOR_DATA_VALUE, "Multiple \"include sensor data\" values to query were given: " + InputKeys.MOBILITY_WITH_SENSOR_DATA); } else if (t.length == 1) { if (MobilityValidators.validateIncludeSensorDataValue(t[0])) { tColumns = MobilityColumnKey.ALL_COLUMNS; } } t = getParameterValues(InputKeys.COLUMN_LIST); if (t.length > 1) { throw new ValidationException(ErrorCode.MOBILITY_INVALID_COLUMN_LIST, "Multiple column lists were given: " + InputKeys.COLUMN_LIST); } else if (t.length == 1) { if (!StringUtils.isEmptyOrWhitespaceOnly(t[0])) { if (tColumns == null) { tColumns = MobilityValidators.validateColumns(t[0], true); } else { throw new ValidationException(ErrorCode.MOBILITY_INVALID_COLUMN_LIST, "Both '" + InputKeys.MOBILITY_WITH_SENSOR_DATA + "' and '" + InputKeys.COLUMN_LIST + "' were present. Only one may be present."); } } } if (tColumns == null) { tColumns = DEFAULT_COLUMNS; } // Get the user. t = getParameterValues(InputKeys.USERNAME); if (t.length > 1) { throw new ValidationException(ErrorCode.USER_INVALID_USERNAME, "Multiple usernames to query were given: " + InputKeys.USERNAME); } else if (t.length == 1) { tUsername = UserValidators.validateUsername(t[0]); } // Always get all of the columns. try { tRegularReadRequest = new StreamReadRequest(httpRequest, getParameterMap(), false, TokenLocation.EITHER, false, tUsername, "edu.ucla.cens.Mobility", null, "regular", 2012050700, tStartDate.minusMinutes(10), tStartDate.plusDays(1), null, true, null, null); tExtendedReadRequest = new StreamReadRequest(httpRequest, getParameterMap(), false, TokenLocation.EITHER, false, tUsername, "edu.ucla.cens.Mobility", null, "extended", 2012050700, tStartDate.minusMinutes(10), tStartDate.plusDays(1), null, true, null, null); } catch (IllegalArgumentException e) { throw new ValidationException("There was an error creating the request.", e); } } catch (ValidationException e) { e.failRequest(this); e.logException(LOGGER); } } username = tUsername; startDate = tStartDate; regularReadRequest = tRegularReadRequest; extendedReadRequest = tExtendedReadRequest; columns = tColumns; points = new ArrayList<MobilityPoint>(); }
From source file:org.openmainframe.ade.ext.main.VerifyLinuxTraining.java
License:Open Source License
/** * Count the number of occurences of unique messages IDs in the given time range * for all of the sources, assumed to be from a single model group. * Also sets the member variables for the number of intervals and the number * of intervals containing messages.//from ww w . j a va 2 s.c o m * * @param sourceSet * @param start * @param end * * @return MessageMetrics - interesting data to use in computing whether the training can proceed. * * @throws AdeException */ private static MessageMetrics computeMessageMetrics(Ade ade, Set<ISource> sourceSet, Date start, Date end) throws AdeException { int numIntervals = 0; int numIntervalsWithMessages = 0; final Map<Integer, Integer> occurrence = new HashMap<Integer, Integer>(); System.out.println("Start computeMessageMetrics "); /* * Get data from the database * * get list of periods from start date to end date for each source */ final Collection<IPeriod> periods = new ArrayList<IPeriod>(); for (ISource source : sourceSet) { periods.addAll(Ade.getAde().getDataStore().periods().getAllPeriods(source, start, end)); } /* return if no periods */ if (periods.isEmpty()) { return new MessageMetrics(0, 0, 0); } /* extract data from the database for each period */ final List<IInterval> curIntervals = new ArrayList<IInterval>(); final Comparator<IInterval> intervalComparator = new Comparator<IInterval>() { @Override public int compare(IInterval int1, IInterval int2) { final long diff = int1.getIntervalStartTime() - int2.getIntervalStartTime(); // Casting to an int isn't a shortcut here. if (diff < 0) { return -1; } else if (diff > 0) { return 1; } else { return 0; } } }; // Periods are days. 120 with default training params for Linux. for (IPeriod period : periods) { final FramingFlowType framingFlowType = Ade.getAde().getFlowFactory().getFlowByName("LINUX") .getMyFramingFlows().get("tenMinutesTrain"); final IAdeIterator<IInterval> iterator = ade.getDataStore().periods().getPeriodIntervals(period, framingFlowType); try { /* For each interval update count of messages * fetch data */ curIntervals.clear(); iterator.open(); // Because intervals overlap (each includes 50 minutes of the previous interval), // we only want to count one interval with messages per hour so sort the intervals // by time and make sure that intervals in the same hour don't increases the amount // of messages multiple times IInterval curInt; while ((curInt = iterator.getNext()) != null) { curIntervals.add(curInt); } Collections.sort(curIntervals, intervalComparator); // We need the total number of intervals for notification messages. numIntervals += curIntervals.size(); DateTime lastIntervalTime = null; boolean addedMessage = false; for (IInterval curInterval : curIntervals) { // Check to see if this interval is for the same hour as the previously processed one, // if it's not set it as the new interval and allow the amount of intervals with messages // to be incremented if (lastIntervalTime == null) { lastIntervalTime = new DateTime(curInterval.getIntervalStartTime()); } else { DateTime currentIntervalTime = new DateTime(curInterval.getIntervalStartTime()); currentIntervalTime = currentIntervalTime .minusMinutes(currentIntervalTime.getMinuteOfHour()) .minusSeconds(currentIntervalTime.getSecondOfMinute()) .minusMillis(currentIntervalTime.getMillisOfSecond()); if (!lastIntervalTime.isEqual(currentIntervalTime)) { lastIntervalTime = currentIntervalTime; addedMessage = false; } } final Collection<IMessageSummary> msgSummaries = curInterval.getMessageSummaries(); if (!msgSummaries.isEmpty() && !addedMessage) { numIntervalsWithMessages++; addedMessage = true; } for (IMessageSummary msgSummary : msgSummaries) { final int msgID = msgSummary.getMessageInternalId(); if (occurrence.containsKey(msgID)) { /* get number of occurrences for this msgID (internal msgID) * increment it and put back again */ occurrence.put(msgID, occurrence.get(msgID) + 1); } else { /* this is first time we see this word, set value '1' */ occurrence.put(msgID, 1); } } } iterator.close(); } finally { iterator.quietCleanup(); } } return new MessageMetrics(occurrence.size(), numIntervalsWithMessages, numIntervals); }
From source file:org.oxymores.chronix.engine.TokenDistributionCenter.java
License:Apache License
@Override public void run() { do {//from w w w . j a va 2 s. co m DateTime now = DateTime.now(); // Sync try { localResource.acquire(); } catch (InterruptedException e1) { // Don't care here, we can loop as we want. log.debug("interrupted, no worries"); } // Renew token location for all boring for (TokenReservation tr : shouldRenew) { if (now.minusMinutes(Constants.TOKEN_RENEWAL_MN).compareTo(new DateTime(tr.getRenewedOn())) <= 0) { try { log.debug("Sending a renewal request for token state"); SenderHelpers.sendTokenRequest(tr.getRenewalRequest(), ctx, jmsSession, jmsProducer, false); } catch (JMSException e) { log.error("Could not send a token renewal request. Will retry soon.", e); } } } jmsCommit(); // Sync localResource.release(); try { // Loop every minute or so. No need to be precise here. if (mainLoop.tryAcquire(Constants.TOKEN_AUTO_RENEWAL_LOOP_PERIOD_S, TimeUnit.SECONDS)) { log.trace("TokenDistributionCenter will loop because engine is stopping"); } } catch (InterruptedException e) { // Once again, who cares? log.debug("interrupted"); } } while (running); }
From source file:org.sonatype.nexus.repository.storage.Asset.java
License:Open Source License
/** * Sets the last accessed timestamp to now, if it has been more than a minute. * * @return {@code true} if the timestamp was changed, otherwise {@code false} *//*from w ww .ja v a2s . co m*/ public boolean markAsAccessed() { DateTime now = DateTime.now(); if (lastAccessed == null || lastAccessed.isBefore(now.minusMinutes(1))) { lastAccessed(now); return true; } return false; }
From source file:org.springframework.analytics.rest.controller.AggregateCounterController.java
License:Apache License
/** * Return a default value for the interval start if none has been provided. *//*from ww w. j a va 2s.co m*/ private DateTime providedOrDefaultFromValue(DateTime from, DateTime to, AggregateCounterResolution resolution) { if (from != null) { return from; } switch (resolution) { case minute: return to.minusMinutes(59); case hour: return to.minusHours(23); case day: return to.minusDays(6); case month: return to.minusMonths(11); case year: return to.minusYears(4); default: throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution); } }