List of usage examples for org.joda.time DateTime plusHours
public DateTime plusHours(int hours)
From source file:com.njlabs.amrita.aid.gpms.client.Gpms.java
License:Open Source License
private DateTime roundOffDate(DateTime target) { int minutes = target.getMinuteOfHour(); if (minutes > 0 && minutes < 15) { return target.withMinuteOfHour(15); } else if (minutes > 15 && minutes < 30) { return target.withMinuteOfHour(30); } else if (minutes > 30 && minutes < 45) { return target.withMinuteOfHour(45); } else if (minutes > 45 && minutes <= 59) { if (target.getHourOfDay() == 23) { return target.plusDays(1).withHourOfDay(0).withMinuteOfHour(0); } else {/*from ww w . j a v a 2 s. c o m*/ return target.plusHours(1).withMinuteOfHour(0); } } else { return target; } }
From source file:com.norconex.collector.http.recrawl.impl.GenericRecrawlableResolver.java
License:Apache License
private boolean isRecrawlableFromFrequency(SitemapChangeFrequency cf, PreviousCrawlData prevData, String context) {//from ww w . ja v a 2 s.c om if (cf == null) { return true; } if (LOG.isDebugEnabled()) { LOG.debug("The " + context + " change frequency is " + cf + " for: " + prevData.getReference()); } if (cf == SitemapChangeFrequency.ALWAYS) { return true; } if (cf == SitemapChangeFrequency.NEVER) { return false; } DateTime minCrawlDate = new DateTime(prevData.getCrawlDate()); switch (cf) { case HOURLY: minCrawlDate = minCrawlDate.plusHours(1); break; case DAILY: minCrawlDate = minCrawlDate.plusDays(1); break; case WEEKLY: minCrawlDate = minCrawlDate.plusWeeks(1); break; case MONTHLY: minCrawlDate = minCrawlDate.plusMonths(1); break; case YEARLY: minCrawlDate = minCrawlDate.plusYears(1); break; default: break; } if (minCrawlDate.isBeforeNow()) { if (LOG.isDebugEnabled()) { LOG.debug("Recrawl suggested according to " + context + " directive (change frequency < elapsed time since " + prevData.getCrawlDate() + ") for: " + prevData.getReference()); } return true; } if (LOG.isDebugEnabled()) { LOG.debug("No recrawl suggested according to " + context + " directive (change frequency >= elapsed time since " + prevData.getCrawlDate() + ") for: " + prevData.getReference()); } return false; }
From source file:com.ofalvai.bpinfo.util.Utils.java
License:Apache License
/** * Returns whether an alert counts as a recent one based on the start timestamp. *///w w w.j a v a 2 s. c o m public static boolean isAlertRecent(@NonNull Alert alert) { DateTime alertTime = new DateTime(alert.getStart() * 1000L); DateTime now = new DateTime(); return alertTime.plusHours(Config.ALERT_RECENT_THRESHOLD_HOURS).getMillis() >= now.getMillis(); }
From source file:com.peertopark.java.dates.Dates.java
License:Apache License
public static DateTime addHours(DateTime date, int hours) { if (Objects.nonNull(date)) { return date.plusHours(hours); } else {/*from www . ja v a 2s. c o m*/ return null; } }
From source file:com.precioustech.fxtrading.oanda.restapi.order.OandaOrderManagementProvider.java
License:Apache License
HttpPost createPostCommand(Order<String, Long> order, Long accountId) throws Exception { HttpPost httpPost = new HttpPost(this.url + OandaConstants.ACCOUNTS_RESOURCE + TradingConstants.FWD_SLASH + accountId + ordersResource); httpPost.setHeader(this.authHeader); List<NameValuePair> params = Lists.newArrayList(); // TODO: apply proper rounding. Oanda rejects 0.960000001 params.add(new BasicNameValuePair(instrument, order.getInstrument().getInstrument())); params.add(new BasicNameValuePair(side, OandaUtils.toSide(order.getSide()))); params.add(new BasicNameValuePair(type, OandaUtils.toType(order.getType()))); params.add(new BasicNameValuePair(units, String.valueOf(order.getUnits()))); params.add(new BasicNameValuePair(takeProfit, String.valueOf(order.getTakeProfit()))); params.add(new BasicNameValuePair(stopLoss, String.valueOf(order.getStopLoss()))); if (order.getType() == OrderType.LIMIT && order.getPrice() != 0.0) { DateTime now = DateTime.now(); DateTime nowplus4hrs = now.plusHours(4);// TODO: why this code // for expiry? String dateStr = nowplus4hrs.toString(); params.add(new BasicNameValuePair(price, String.valueOf(order.getPrice()))); params.add(new BasicNameValuePair(expiry, dateStr)); }/* w ww .j a v a 2s . co m*/ httpPost.setEntity(new UrlEncodedFormEntity(params)); return httpPost; }
From source file:com.quinsoft.zeidon.domains.DateTimeDomain.java
License:Open Source License
private Object addWithContext(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef, Object currentValue, Object operand, String contextName) { assert !StringUtils.isBlank(contextName); if (operand instanceof AttributeInstance) operand = ((AttributeInstance) operand).getValue(); if (!(operand instanceof Integer) && !(operand instanceof Long)) { throw new ZeidonException( "When adding to DateTime with a context, operand must be integer or long value. " + "Type of operand = %s", operand.getClass().getName()).prependAttributeDef(attributeDef); }//from www.j a v a2s. c o m int value = ((Number) operand).intValue(); DateTime dt = (DateTime) currentValue; switch (contextName.toLowerCase()) { case "day": case "days": return dt.plusDays(value); case "hour": case "hours": return dt.plusHours(value); case "minute": case "minutes": return dt.plusMinutes(value); case "milli": case "millis": case "millisecond": case "milliseconds": return dt.plus(((Number) operand).longValue()); case "month": case "months": return dt.plusMonths(value); case "second": case "seconds": return dt.plusSeconds(value); case "week": case "weeks": return dt.plusWeeks(value); case "year": case "years": return dt.plusYears(value); } // TODO Auto-generated method stub throw new ZeidonException("Unknown context name '%s' for DateTime domain", contextName) .prependAttributeDef(attributeDef); }
From source file:com.sonicle.webtop.tasks.TasksManager.java
License:Open Source License
public List<BaseReminder> getRemindersToBeNotified(DateTime now) { ArrayList<BaseReminder> alerts = new ArrayList<>(); HashMap<UserProfileId, Boolean> byEmailCache = new HashMap<>(); TaskDAO dao = TaskDAO.getInstance(); Connection con = null;// w ww.j a va 2s .c o m try { con = WT.getConnection(SERVICE_ID); con.setAutoCommit(false); DateTime now12 = now.plusHours(14); List<VTask> tasks = dao.viewExpridedForUpdateByUntil(con, now12); DateTime profileNow = null, profileReminderDate = null; for (VTask task : tasks) { UserProfile.Data ud = WT.getUserData(task.getCategoryProfileId()); profileNow = now.withZone(ud.getTimeZone()); profileReminderDate = task.getReminderDate().withZone(DateTimeZone.UTC) .withZoneRetainFields(ud.getTimeZone()); if (profileReminderDate.isAfter(profileNow)) continue; if (!byEmailCache.containsKey(task.getCategoryProfileId())) { TasksUserSettings us = new TasksUserSettings(SERVICE_ID, task.getCategoryProfileId()); boolean bool = us.getTaskReminderDelivery().equals(TasksSettings.TASK_REMINDER_DELIVERY_EMAIL); byEmailCache.put(task.getCategoryProfileId(), bool); } int ret = dao.updateRemindedOn(con, task.getTaskId(), now); if (ret != 1) continue; if (byEmailCache.get(task.getCategoryProfileId())) { alerts.add( createTaskReminderAlertEmail(ud.toProfileI18n(), task, ud.getPersonalEmailAddress())); } else { alerts.add(createTaskReminderAlertWeb(ud.toProfileI18n(), task, profileReminderDate)); } } DbUtils.commitQuietly(con); } catch (Exception ex) { logger.error("Error collecting reminder alerts", ex); } finally { DbUtils.closeQuietly(con); } return alerts; }
From source file:com.startupbidder.dao.MockDataBuilder.java
private Listing prepareListing(UserVO owner, String name, Listing.State state, String category, int amount, int percentage, String mantra, String summary, String companyUrl, DateTime createdAt, DateTime modifiedAt, String logo_url, String address) { Listing bp = new Listing(); bp.id = id();/*from w w w.j av a2 s . c om*/ bp.name = name; bp.summary = summary; bp.mantra = mantra; bp.owner = new Key<SBUser>(SBUser.class, owner.toKeyId()); bp.contactEmail = owner.getEmail(); bp.founders = getFounders(owner.getName()); bp.type = Listing.Type.COMPANY; bp.notes = "Mock listing.\n"; bp.askedForFunding = amount > 0; bp.suggestedAmount = amount; bp.suggestedPercentage = percentage; bp.category = category; bp.state = state; int hours = new Random().nextInt(500) + 80; DateTime createdTime = createdAt != null ? createdAt : new DateTime().minusHours(hours); if (modifiedAt != null) { bp.modified = modifiedAt.toDate(); } bp.created = createdTime.toDate(); switch (state) { case NEW: break; case POSTED: bp.posted = createdTime.plusHours(hours * 5 / 10).toDate(); break; case ACTIVE: case FROZEN: bp.posted = createdTime.plusHours(hours * 7 / 10).toDate(); bp.listedOn = createdTime.plusHours(hours * 4 / 10).toDate(); if (bp.askedForFunding) { bp.closingOn = createdTime.plusHours(hours * 4 / 10).plusDays(30).toDate(); } break; case WITHDRAWN: bp.posted = createdTime.plusHours(hours * 8 / 10).toDate(); bp.listedOn = createdTime.plusHours(hours * 6 / 10).toDate(); bp.closingOn = createdTime.plusHours(hours * 6 / 10).plusDays(30).toDate(); break; case CLOSED: hours = new Random().nextInt(500) + 33 * 24; createdTime = new DateTime().minusHours(hours); bp.created = createdTime.toDate(); bp.posted = createdTime.plusHours(24).toDate(); bp.listedOn = createdTime.plusHours(48).toDate(); bp.closingOn = createdTime.plusDays(32).toDate(); break; } GeocodeLocation location = null; if (address != null) { location = getGeocodedLocation(address); location.randomize(0.1); } if (location == null) { location = getRandomLocation(); location.randomize(0.001); } bp.address = location.address; bp.city = location.city; bp.usState = "USA".equals(location.country) ? location.state : null; bp.country = location.country; DtoToVoConverter.updateBriefAddress(bp); bp.latitude = location.latitude; bp.longitude = location.longitude; bp.videoUrl = getVideo(); bp.website = !StringUtils.isEmpty(companyUrl) ? companyUrl : getWebsite(); bp.answer1 = getQuote(); bp.answer2 = getQuote(); bp.answer3 = getQuote(); bp.answer4 = getQuote(); bp.answer5 = getQuote(); bp.answer6 = getQuote(); bp.answer7 = getQuote(); bp.answer8 = getQuote(); bp.answer9 = getQuote(); bp.answer10 = getQuoteWithNulls(); bp.answer11 = getQuoteWithNulls(); bp.answer12 = getQuoteWithNulls(); bp.answer13 = getQuoteWithNulls(); bp.answer14 = getQuoteWithNulls(); bp.answer15 = getQuoteWithNulls(); bp.answer16 = getQuoteWithNulls(); bp.answer17 = getQuoteWithNulls(); bp.answer18 = getQuoteWithNulls(); bp.answer19 = getQuoteWithNulls(); bp.answer20 = getQuoteWithNulls(); bp.answer21 = getQuoteWithNulls(); bp.answer22 = getQuoteWithNulls(); bp.answer23 = getQuoteWithNulls(); bp.answer24 = getQuoteWithNulls(); bp.answer25 = getQuoteWithNulls(); bp.answer26 = getQuoteWithNulls(); if (!StringUtils.isEmpty(logo_url)) { logo_url = logo_url.replaceAll("^https://", "http://"); logoUrls.put(bp.id, logo_url); } return bp; }
From source file:com.tango.elasticsearch.rest.action.unique.UniqueTermsAction.java
License:Apache License
private void prepareRequestsForProcessing(RestRequest request, Map<SearchRequest, String> searchRequestsToCacheKeyMap, List<TermsResult> cachedResponses) throws IOException { SearchRequest searchRequest = RestSearchAction.parseSearchRequest(request); String[] indices = searchRequest.indices(); if (searchRequest.source() == null) { throw new IllegalArgumentException("Empty request source"); }/* w ww .j a v a 2 s .c o m*/ RequestParamsInfo requestParamsInfo = getRequestInfo( new String(searchRequest.source().copyBytesArray().array())); if (request.paramAsBoolean("clearCache", false)) { cache.clear(); } searchRequest.listenerThreaded(false); for (String index : indices) { String cacheKey = ""; if (requestParamsInfo != null) { boolean cachedValueFound = false; int datePostfixStart; while ((datePostfixStart = index.indexOf(INDEX_NAME_PREFIX_DELIMITER)) >= 0) { String dateStr = index.substring(datePostfixStart + 1); try { DateTime dateTime = ES_INDEX_DATE_FORMAT.parseDateTime(dateStr); long indexStart = dateTime.getMillis(); // plus 1 hour long indexEnd = dateTime.plusHours(1).getMillis(); // fully covered if (indexStart >= requestParamsInfo.getFromTime() && indexEnd < requestParamsInfo.getToTime()) { // trying to get from cache cacheKey = index + requestParamsInfo.getRequestCacheKey(); TermsResult cached = getCachedValue(cacheKey); if (cached != null) { cachedValueFound = true; cachedResponses.add(cached); } } break; } catch (IllegalArgumentException ex) { if (logger.isTraceEnabled()) { logger.trace("Error parsing date from " + dateStr + ": " + ex.getMessage(), ex); } } } if (cachedValueFound) { continue; } } SearchRequest oneIndexSearchRequest = new SearchRequest(index); if (searchRequest.source() != null) { oneIndexSearchRequest.source(searchRequest.source().copyBytesArray().array()); } if (searchRequest.extraSource() != null) { oneIndexSearchRequest.extraSource(searchRequest.extraSource().copyBytesArray().array()); } oneIndexSearchRequest.searchType(searchRequest.searchType()); oneIndexSearchRequest.types(searchRequest.types()); oneIndexSearchRequest.routing(searchRequest.routing()); oneIndexSearchRequest.preference(searchRequest.preference()); oneIndexSearchRequest.ignoreIndices(searchRequest.ignoreIndices()); oneIndexSearchRequest.listenerThreaded(false); oneIndexSearchRequest.operationThreading(searchRequest.operationThreading()); searchRequestsToCacheKeyMap.put(oneIndexSearchRequest, cacheKey); } }
From source file:com.thinkbiganalytics.metadata.jobrepo.nifi.provenance.NifiStatsJmsReceiver.java
License:Apache License
/** * the BulletinDTO comes back from nifi as a Date object in the year 1970 * We need to convert this to the current date and account for DST * * @param b the bulletin/*from w w w. j av a 2s. c o m*/ */ private DateTime getAdjustBulletinDateTime(BulletinDTO b) { DateTimeZone defaultZone = DateTimeZone.getDefault(); int currentOffsetMillis = defaultZone.getOffset(DateTime.now().getMillis()); double currentOffsetHours = (double) currentOffsetMillis / 1000d / 60d / 60d; long bulletinOffsetMillis = DateTimeZone.getDefault().getOffset(b.getTimestamp().getTime()); double bulletinOffsetHours = (double) bulletinOffsetMillis / 1000d / 60d / 60d; DateTime adjustedTime = new DateTime(b.getTimestamp()).withDayOfYear(DateTime.now().getDayOfYear()) .withYear(DateTime.now().getYear()); int adjustedHours = 0; if (currentOffsetHours != bulletinOffsetHours) { adjustedHours = new Double(bulletinOffsetHours - currentOffsetHours).intValue(); adjustedTime = adjustedTime.plusHours(-adjustedHours); } return adjustedTime; }