Java Code Examples for org.joda.time.DateTimeComparator

The following are top voted examples for showing how to use org.joda.time.DateTimeComparator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: Fudan-Sakai   File: EventSummary.java View source code 6 votes vote down vote up
private boolean isToday(long dateMs) {
	TimeZone timeZone = getCurrentUserTimezone();
	DateTime thisDate = new DateTime(dateMs).withZone(DateTimeZone.forTimeZone(timeZone));
	//Start of day at this local
	DateTime today = new DateTime().withTime(0, 0, 0, 0).withZone(DateTimeZone.forTimeZone(timeZone));
	DateTimeComparator dtComp = DateTimeComparator.getDateOnlyInstance();
	return  (dtComp.compare(thisDate, today) == 0);
	
}
 
Example 2
Project: sakai-cle   File: EventSummary.java View source code 6 votes vote down vote up
private boolean isToday(long dateMs) {
	TimeZone timeZone = getCurrentUserTimezone();
	DateTime thisDate = new DateTime(dateMs).withZone(DateTimeZone.forTimeZone(timeZone));
	//Start of day at this local
	DateTime today = new DateTime().withTime(0, 0, 0, 0).withZone(DateTimeZone.forTimeZone(timeZone));
	DateTimeComparator dtComp = DateTimeComparator.getDateOnlyInstance();
	return  (dtComp.compare(thisDate, today) == 0);
	
}
 
Example 3
Project: fluxtream-app   File: BodymediaUpdater.java View source code 6 votes vote down vote up
void updateStartDate(UpdateInfo updateInfo, ObjectType ot, DateTime updateProgressTime)
{
    DateTimeComparator comparator = DateTimeComparator.getDateOnlyInstance();

    // Calculate the name of the key in the ApiAttributes table
    // where the next start of update for this object type is
    // stored and retrieve the stored value.  This stored value
    // may potentially be null if something happened to the attributes table
    String updateKeyName = "BodyMedia." + ot.getName() + ".updateStartDate";
    String storedUpdateStartDate = guestService.getApiKeyAttribute(updateInfo.apiKey, updateKeyName);

    // Retrieve the lastSync date if it has been added to the
    // updateInfo context by an extractor
    DateTime lastSync = (DateTime)updateInfo.getContext("lastSync");


    // Check which is earlier: the lastSync time returned from Bodymedia or the
    // point we were in the update that just ended.  Store the lesser of the two
    // in nextUpdateStartDate
    String nextUpdateStartDate = storedUpdateStartDate;
    if (lastSync != null) {
        if (comparator.compare(updateProgressTime, lastSync) > 0) {
            // lastSync from Bodymedia is less than the update progress
            nextUpdateStartDate = lastSync.toString(formatter);
        }
        else {
            // the update progress is less than lastSync from Bodymedia
            nextUpdateStartDate = updateProgressTime.toString(formatter);
        }
    }
    else {
        // Last sync is null, just leave the stored updateTime
        // alone since it's better to get some extra data next
        // time than to skip data from dates that potentially changed
    }

    // Store the new value if it's different than what's stored in ApiKeyAttributes
    if(storedUpdateStartDate==null || !nextUpdateStartDate.equals(storedUpdateStartDate)) {
        guestService.setApiKeyAttribute(updateInfo.apiKey, updateKeyName, nextUpdateStartDate);
    }
}
 
Example 4
Project: cassandra-reaper   File: RepairRun.java View source code 6 votes vote down vote up
/**
 * Order RepairRun instances by time. Primarily endTime, secondarily startTime. Descending, i.e.
 * latest first.
 * @param other the RepairRun compared to
 * @return negative if this RepairRun is later than the specified RepairRun. Positive if earlier.
 *         0 if equal.
 */
@Override
public int compareTo(RepairRun other) {
  DateTimeComparator comparator = DateTimeComparator.getInstance();
  int endTimeComparison = comparator.compare(endTime, other.endTime);
  if (endTimeComparison != 0) {
    return -endTimeComparison;
  } else {
    return -comparator.compare(startTime, other.startTime);
  }
}
 
Example 5
Project: togg   File: DateTimeFormatter.java View source code 6 votes vote down vote up
public static String dayOrDate(Date date) {
    int actualDayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
    int actualYear = Calendar.getInstance().get(Calendar.YEAR);
    Calendar c = Calendar.getInstance();
    c.setTime(date);

    DateTimeComparator comparator = DateTimeComparator
            .getDateOnlyInstance();

    String result;
    if (comparator.compare(date, new Date()) == 0) {
        result = ToggApp.getApplication().getResources()
                .getString(R.string.today);
    } else if (actualYear == c.get(Calendar.YEAR)
            && actualDayOfYear - c.get(Calendar.DAY_OF_YEAR) == 1) {
        result = ToggApp.getApplication().getResources()
                .getString(R.string.yesterday);
    } else {
        result = literalDate(date);
    }

    return result;
}
 
Example 6
Project: nazgul_core   File: DateTimeProperty.java View source code 6 votes vote down vote up
/**
 * Equality comparison definition that compares key and value.
 * {@inheritDoc}
 */
@Override
public boolean equals(final Object that) {

    // Check sanity
    if (that == null || !that.getClass().equals(DateTimeProperty.class)) {
        return false;
    }
    if (this == that) {
        return true;
    }

    // Delegate
    final DateTimeProperty thatProperty = (DateTimeProperty) that;
    final DateTimeComparator comparator = DateTimeComparator.getInstance();

    boolean valuesAreEqual = getValue() == null
            ? thatProperty.getValue() == null
            : comparator.compare(getValue(), thatProperty.getValue()) == 0;

    return getKey().equals(thatProperty.getKey()) && valuesAreEqual;
}
 
Example 7
Project: cryptosms   File: Conversation.java View source code 6 votes vote down vote up
@Override
public int compareTo(Conversation another) {
	try {
		return DateTimeComparator.getInstance().compare(this.getTimeStamp(), another.getTimeStamp());
	} catch (Exception e) {
		return 0;
	}
}
 
Example 8
Project: cryptosms   File: MessageData_Test.java View source code 6 votes vote down vote up
private void checkData(MessageData msg) {
	assertEquals(msg.getDeliveredPart(), deliveredPart);
	assertEquals(msg.getDeliveredAll(), deliveredAll);
	assertEquals(msg.getMessageType(), messageType);
	assertEquals(msg.getUnread(), unread);
	assertEquals(msg.getCompressed(), compressed);
	assertEquals(msg.getAscii(), ascii);
	assertEquals(DateTimeComparator.getInstance().compare(msg.getTimeStamp(), timeStamp), 0);
	assertEquals(msg.getMessageBody().length, messageBodyLength);
	CustomAsserts.assertArrayEquals(msg.getMessageBody(), messageBodyData);
	assertEquals(msg.getIndexParent(), indexParent);
	assertEquals(msg.getIndexMessageParts(), indexMessageParts);
	assertEquals(msg.getIndexPrev(), indexPrev);
	assertEquals(msg.getIndexNext(), indexNext);
}
 
Example 9
Project: druid   File: IndexGeneratorJobTest.java View source code 6 votes vote down vote up
private Map<DateTime, List<HadoopyShardSpec>> loadShardSpecs(
    String partitionType,
    Object[][][] shardInfoForEachShard
)
{
  Map<DateTime, List<HadoopyShardSpec>> shardSpecs = Maps.newTreeMap(DateTimeComparator.getInstance());
  int shardCount = 0;
  int segmentNum = 0;
  for (Interval segmentGranularity : config.getSegmentGranularIntervals().get()) {
    List<ShardSpec> specs = constructShardSpecFromShardInfo(partitionType, shardInfoForEachShard[segmentNum++]);
    List<HadoopyShardSpec> actualSpecs = Lists.newArrayListWithExpectedSize(specs.size());
    for (int i = 0; i < specs.size(); ++i) {
      actualSpecs.add(new HadoopyShardSpec(specs.get(i), shardCount++));
    }

    shardSpecs.put(segmentGranularity.getStart(), actualSpecs);
  }

  return shardSpecs;
}
 
Example 10
Project: druid   File: HadoopDruidDetermineConfigurationJob.java View source code 6 votes vote down vote up
@Override
public boolean run()
{
  List<Jobby> jobs = Lists.newArrayList();

  JobHelper.ensurePaths(config);

  if (config.isDeterminingPartitions()) {
    jobs.add(config.getPartitionsSpec().getPartitionJob(config));
  } else {
    int shardsPerInterval = config.getPartitionsSpec().getNumShards();
    Map<DateTime, List<HadoopyShardSpec>> shardSpecs = Maps.newTreeMap(DateTimeComparator.getInstance());
    int shardCount = 0;
    for (Interval segmentGranularity : config.getSegmentGranularIntervals().get()) {
      DateTime bucket = segmentGranularity.getStart();
      if (shardsPerInterval > 0) {
        List<HadoopyShardSpec> specs = Lists.newArrayListWithCapacity(shardsPerInterval);
        for (int i = 0; i < shardsPerInterval; i++) {
          specs.add(
              new HadoopyShardSpec(
                  new HashBasedNumberedShardSpec(i, shardsPerInterval, HadoopDruidIndexerConfig.JSON_MAPPER),
                  shardCount++
              )
          );
        }
        shardSpecs.put(bucket, specs);
        log.info("DateTime[%s], spec[%s]", bucket, specs);
      } else {
        final HadoopyShardSpec spec = new HadoopyShardSpec(new NoneShardSpec(), shardCount++);
        shardSpecs.put(bucket, Lists.newArrayList(spec));
        log.info("DateTime[%s], spec[%s]", bucket, spec);
      }
    }
    config.setShardSpecs(shardSpecs);
  }

  return JobHelper.runJobs(jobs, config);

}
 
Example 11
Project: fluxtream-app   File: BodymediaUpdater.java View source code 5 votes vote down vote up
/**
 * Retrieves that history for the given facet from the start date to the end date. It peforms the api calls in reverse order
 * starting from the end date. This is so that the most recent information is retrieved first.
 * @param updateInfo The api's info
 * @param ot The ObjectType that represents the facet to be updated
 * @param start The earliest date for which the burn history is retrieved. This date is included in the update.
 * @param end The latest date for which the burn history is retrieved. This date is also included in the update.
 * @throws Exception If either storing the data fails or if the rate limit is reached on Bodymedia's api
 */
private void retrieveHistory(UpdateInfo updateInfo, ObjectType ot, DateTime start, DateTime end) throws Exception {
    final String urlExtension = url.get(ot);
    final int increment = maxIncrement.get(ot);
    DateTimeComparator comparator = DateTimeComparator.getDateOnlyInstance();
    DateTime current = start;

    // Setup the rate delay if we haven't already
    Long rateDelay = getRateDelay(updateInfo);

    try {
        //  Loop from start to end, incrementing by the max number of days you can
        //  specify for a given type of query.  This is 1 for burn and sleep, and 31 for steps.
        //@ loop_invariant date.compareTo(userRegistrationDate) >= 0;
        while (comparator.compare(current, end) < 0)
        {
            if (guestService.getApiKey(updateInfo.apiKey.getId())==null) {
                logger.info("Not updating BodyMedia connector instance with a deleted apiKeyId");
                return;
            }
            String startPeriod = current.toString(formatter);
            String endPeriod = current.plusDays(increment - 1).toString(formatter);
            String minutesUrl = "http://api.bodymedia.com/v2/json/" + urlExtension + startPeriod + "/" + endPeriod +
                                "?api_key=" + guestService.getApiKeyAttribute(updateInfo.apiKey, "bodymediaConsumerKey");
            //The following call may fail due to bodymedia's api. That is expected behavior
            enforceRateLimits(rateDelay);
            String json = signpostHelper.makeRestCall(updateInfo.apiKey, ot.value(), minutesUrl);
            guestService.setApiKeyAttribute(updateInfo.apiKey, "timeOfLastCall", String.valueOf(System.currentTimeMillis()));
            JSONObject bodymediaResponse = JSONObject.fromObject(json);
            JSONArray daysArray = bodymediaResponse.getJSONArray("days");
            if(bodymediaResponse.has("lastSync"))
            {
                DateTime d = form.parseDateTime(bodymediaResponse.getJSONObject("lastSync").getString("dateTime"));

                // Get timezone map from UpdateInfo context
                TimezoneMap tzMap = (TimezoneMap)updateInfo.getContext("tzMap");

                // Insert lastSync into the updateInfo context so it's accessible to the updater
                updateInfo.setContext("lastSync", d);
                List<AbstractFacet> newFacets = new ArrayList<AbstractFacet>();
                for(Object o : daysArray)
                {
                    if(o instanceof JSONObject)
                    {
                        if (ot==ObjectType.getObjectType(connector(), "steps"))
                            newFacets.add(createOrUpdateStepsFacet((JSONObject)o, updateInfo, d, tzMap));
                        else if (ot==ObjectType.getObjectType(connector(), "burn"))
                            newFacets.add(createOrUpdateBurnFacet((JSONObject)o, updateInfo, d, tzMap));
                        else
                            newFacets.add(createOrUpdateSleepFacet((JSONObject)o, updateInfo, d, tzMap));
                    }
                }
                bodyTrackStorageService.storeApiData(updateInfo.apiKey, newFacets);
            }

            current = current.plusDays(increment);

            // Update the stored value that controls when we will start updating next time
            updateStartDate(updateInfo,ot,current);
        }

    }
    catch (Exception e) {
        StringBuilder sb = new StringBuilder("module=updateQueue component=updater action=BodymediaUpdater.retrieveHistory")
                                            .append(" message=\"exception while retrieving history\" connector=")
                                            .append(updateInfo.apiKey.getConnector().toString())
                                            .append(" guestId=").append(updateInfo.apiKey.getGuestId())
                                            .append(" updatingDate=").append(current);
        logger.info(sb.toString());

        // Update the stored value that controls when we will start updating next time
        updateStartDate(updateInfo,ot,current);

        // Rethrow the error so that this task gets rescheduled
        throw e;
    }

}