Java Code Examples for org.joda.time.DateTimeZone#UTC

The following examples show how to use org.joda.time.DateTimeZone#UTC . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Arja_00172_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Decodes a built DateTimeZone from the given stream, as encoded by
 * writeTo.
 *
 * @param in input stream to read encoded DateTimeZone from.
 * @param id time zone id to assign
 */
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
    switch (in.readUnsignedByte()) {
    case 'F':
        DateTimeZone fixed = new FixedDateTimeZone
            (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
        if (fixed.equals(DateTimeZone.UTC)) {
            fixed = DateTimeZone.UTC;
        }
        return fixed;
    case 'C':
        return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
    case 'P':
        return PrecalculatedZone.readFrom(in, id);
    default:
        throw new IOException("Invalid encoding");
    }
}
 
Example 2
Source File: Arja_00172_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Decodes a built DateTimeZone from the given stream, as encoded by
 * writeTo.
 *
 * @param in input stream to read encoded DateTimeZone from.
 * @param id time zone id to assign
 */
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
    switch (in.readUnsignedByte()) {
    case 'F':
        DateTimeZone fixed = new FixedDateTimeZone
            (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
        if (fixed.equals(DateTimeZone.UTC)) {
            fixed = DateTimeZone.UTC;
        }
        return fixed;
    case 'C':
        return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
    case 'P':
        return PrecalculatedZone.readFrom(in, id);
    default:
        throw new IOException("Invalid encoding");
    }
}
 
Example 3
Source File: PostSubscriptionControllerTest.java    From nakadi with MIT License 6 votes vote down vote up
@Test
public void whenSubscriptionExistsThenReturnIt() throws Exception {
    final SubscriptionBase subscriptionBase = RandomSubscriptionBuilder.builder().buildSubscriptionBase();
    final DateTime createdAt = new DateTime(DateTimeZone.UTC);
    final Subscription existingSubscription = new Subscription("123", createdAt, createdAt, subscriptionBase);

    when(subscriptionService.getExistingSubscription(any())).thenReturn(existingSubscription);
    when(subscriptionService.createSubscription(any())).thenThrow(new NoSuchEventTypeException("msg"));

    postSubscription(subscriptionBase)
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
            .andExpect(content().string(
                    SameJSONAs.sameJSONAs(TestUtils.JSON_TEST_HELPER.asJsonString(existingSubscription))))
            .andExpect(header().string("Location", "/subscriptions/123"))
            .andExpect(header().doesNotExist("Content-Location"));
}
 
Example 4
Source File: XdrStreamIteratorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    final DateTime now = new DateTime(DateTimeZone.UTC);

    tsdata = new ArrayList<>();
    for (int i = 0; i < 100; ++i) {
        tsdata.add(new SimpleTimeSeriesCollection(now.plusMinutes(i), Stream.of(
                new ImmutableTimeSeriesValue(
                        GroupName.valueOf(SimpleGroupPath.valueOf("foo", "bar")),
                        singletonMap(MetricName.valueOf("x"), MetricValue.fromIntValue(i))))));
    }

    tmpdir = Files.createTempDirectory("monsoon-XdrStreamIteratorTest");
    tmpfile = tmpdir.resolve("test.tsv");
    file_support.create_file(tmpfile, tsdata);
}
 
Example 5
Source File: CronSchedule.java    From celos with Apache License 2.0 5 votes vote down vote up
private DateTime getNextDateTime(DateTime candidate) {
    Date date = cronExpression.getNextValidTimeAfter(candidate.toDate());
    if (date != null) {
        return new DateTime(date, DateTimeZone.UTC);
    } else {
        return null;
    }
}
 
Example 6
Source File: Jackson2ObjectMapperBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test // SPR-12634
public void customizeWellKnownModulesWithModule() throws JsonProcessingException, UnsupportedEncodingException {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.modulesToInstall(new CustomIntegerModule()).build();
	DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
	assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8"));
	assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid"));
}
 
Example 7
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-12634
@SuppressWarnings("unchecked")
public void customizeDefaultModulesWithModuleClass() throws JsonProcessingException, UnsupportedEncodingException {
	this.factory.setModulesToInstall(CustomIntegerModule.class);
	this.factory.afterPropertiesSet();
	ObjectMapper objectMapper = this.factory.getObject();

	DateTime dateTime = new DateTime(1322903730000L, DateTimeZone.UTC);
	assertEquals("1322903730000", new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8"));
	assertThat(new String(objectMapper.writeValueAsBytes(new Integer(4)), "UTF-8"), containsString("customid"));
}
 
Example 8
Source File: LLCSegmentName.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public LLCSegmentName(String tableName, int partitionId, int sequenceNumber, long msSinceEpoch) {
  if (!isValidComponentName(tableName)) {
    throw new RuntimeException("Invalid table name " + tableName);
  }
  _tableName = tableName;
  _partitionId = partitionId;
  _sequenceNumber = sequenceNumber;
  // ISO8601 date: 20160120T1234Z
  DateTime dateTime = new DateTime(msSinceEpoch, DateTimeZone.UTC);
  _creationTime = dateTime.toString("yyyyMMdd'T'HHmm'Z'");
  _segmentName = tableName + SEPARATOR + partitionId + SEPARATOR + sequenceNumber + SEPARATOR + _creationTime;
}
 
Example 9
Source File: Nopol2017_0085_s.java    From coming with MIT License 5 votes vote down vote up
private static DateTimeZone buildFixedZone(String id, String nameKey,
                                           int wallOffset, int standardOffset) {
    if ("UTC".equals(id) && id.equals(nameKey) &&
        wallOffset == 0 && standardOffset == 0) {
        return DateTimeZone.UTC;
    }
    return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset);
}
 
Example 10
Source File: LenientChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public Chronology withZone(DateTimeZone zone) {
    if (zone == null) {
        zone = DateTimeZone.getDefault();
    }
    if (zone == DateTimeZone.UTC) {
        return withUTC();
    }
    if (zone == getZone()) {
        return this;
    }
    return LenientChronology.getInstance(getBase().withZone(zone));
}
 
Example 11
Source File: WithTimeZone.java    From presto with Apache License 2.0 5 votes vote down vote up
private static LongTimestampWithTimeZone toLong(long epochMicros, int picosOfMicro, Slice zoneId, ConnectorSession session)
{
    TimeZoneKey toTimeZoneKey = getTimeZoneKey(zoneId.toStringUtf8());
    DateTimeZone fromDateTimeZone = session.isLegacyTimestamp() ? getDateTimeZone(session.getTimeZoneKey()) : DateTimeZone.UTC;
    DateTimeZone toDateTimeZone = getDateTimeZone(toTimeZoneKey);

    long epochMillis = scaleEpochMicrosToMillis(epochMicros);
    epochMillis = fromDateTimeZone.getMillisKeepLocal(toDateTimeZone, epochMillis);

    int picosOfMilli = getMicrosOfMilli(epochMicros) * PICOSECONDS_PER_MICROSECOND + picosOfMicro;
    return LongTimestampWithTimeZone.fromEpochMillisAndFraction(epochMillis, picosOfMilli, toTimeZoneKey);
}
 
Example 12
Source File: AlarmServiceModel.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
public AlarmServiceModel(Document doc) {
    if (doc != null) {
        this.eTag = doc.getETag();
        this.id = doc.getId();
        this.dateCreated = new DateTime(doc.getLong("created"), DateTimeZone.UTC);
        this.dateModified = new DateTime(doc.getLong("modified"), DateTimeZone.UTC);
        this.description = doc.getString("description");
        this.groupId = doc.getString("group.id");
        this.deviceId = doc.getString("device.id");
        this.status = doc.getString("status");
        this.ruleId = doc.getString("rule.id");
        this.ruleSeverity = doc.getString("rule.severity");
        this.ruleDescription = doc.getString("rule.description");
    } else {
        this.eTag = null;
        this.id = null;
        this.dateCreated = null;
        this.dateModified = null;
        this.description = null;
        this.groupId = null;
        this.deviceId = null;
        this.status = null;
        this.ruleId = null;
        this.ruleSeverity = null;
        this.ruleDescription = null;
    }
}
 
Example 13
Source File: DateTimePeriodSelectorTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void lastMonth() throws Exception {
    DateTimePeriod period = DateTimePeriodSelector.lastMonth(DateTimeZone.UTC);
    DateTime now = new DateTime(DateTimeZone.UTC);
    now = now.minusMonths(1);
    DateTimePeriod expectedPeriod = DateTimePeriod.createMonth(now.getYear(), now.getMonthOfYear(), DateTimeZone.UTC);

    Assert.assertEquals(expectedPeriod, period);
}
 
Example 14
Source File: DeletedStorageAccountItem.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
/**
 * Get the scheduledPurgeDate value.
 *
 * @return the scheduledPurgeDate value
 */
public DateTime scheduledPurgeDate() {
    if (this.scheduledPurgeDate == null) {
        return null;
    }
    return new DateTime(this.scheduledPurgeDate * 1000L, DateTimeZone.UTC);
}
 
Example 15
Source File: RecruitmentController.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
private static boolean canRecruit(Connection conn, int region) throws SQLException {
	try (PreparedStatement lastRecruitment = conn.prepareStatement("SELECT timestamp, confirmed FROM assembly.recruitment_results WHERE region = ? ORDER BY timestamp DESC LIMIT 0, 1")) {
		lastRecruitment.setInt(1, region);
		try (ResultSet recruitment = lastRecruitment.executeQuery()) {
			if (recruitment.next()) {
				long timestamp = recruitment.getLong(1);
				int confirmed = recruitment.getInt(2);
				
				final DateTime time = new DateTime(timestamp, DateTimeZone.UTC);
				if (confirmed == 1 && time.plus(SAFETY_FACTOR).plus(Duration.standardMinutes(3)).isBefore(DateTime.now(DateTimeZone.UTC))) {
					logger.trace("Recruitment is possible for region [{}], last confirmed recruitment was at {}", region, time);
					return true;
				} else if (confirmed == 0 && time.plus(SAFETY_FACTOR).plus(Duration.standardMinutes(4)).isBefore(DateTime.now(DateTimeZone.UTC))) {
					logger.trace("Recruitment is possible for region [{}], last unconfirmed recruitment was at {}", region, time);
					return true;
				} else if (confirmed == -1 && time.plus(SAFETY_FACTOR).plus(Duration.standardMinutes(5)).isBefore(DateTime.now(DateTimeZone.UTC))) {
					logger.trace("Recruitment should be possible for region [{}], last recruitment attempt was at {}", region, time);
					return true;
				} else if (time.isAfter(DateTime.now())) {
					logger.warn("System clock unreliable! Database last recruitment time is AFTER current time, database is in the future!");
					return false;
				} else {
					logger.trace("Recruitment is NOT possible for region [{}], last recruitment was at {} and confirmation status is {} (current time is {})", region, time, confirmed, DateTime.now(DateTimeZone.UTC));
					return false;
				}
			} else {
				logger.trace("Recruitment is possible for region [{}], no previous recruitment attempts", region);
				return true;
			}
		}
	}
}
 
Example 16
Source File: TiConstantTest.java    From tikv-client-lib-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testEncodeSQLDate() {
  DateWrapper[] wrappers = new DateWrapper[]{
      new DateWrapper(904694400000L),
      new DateWrapper(946684800000L),
      new DateWrapper(1077984000000L),
      new DateWrapper(-1019721600000L),
      new DateWrapper(1488326400000L),
  };

  DateTimeZone timeZone = DateTimeZone.UTC;
  LocalDate[] localDates = new LocalDate[]{
      new LocalDate(904694400000L, timeZone),
      new LocalDate(946684800000L, timeZone),
      new LocalDate(1077984000000L, timeZone),
      new LocalDate(-1019721600000L, timeZone),
      new LocalDate(1488326400000L, timeZone),
  };

  String[] encodeAnswers = new String[]{
      "tp: MysqlTime\nval: \"\\031_\\304\\000\\000\\000\\000\\000\"\n",
      "tp: MysqlTime\nval: \"\\031dB\\000\\000\\000\\000\\000\"\n",
      "tp: MysqlTime\nval: \"\\031q\\270\\000\\000\\000\\000\\000\"\n",
      "tp: MysqlTime\nval: \"\\030\\231\\220\\000\\000\\000\\000\\000\"\n",
      "tp: MysqlTime\nval: \"\\031\\234\\002\\000\\000\\000\\000\\000\"\n",
  };

  String[][] answers = {
      {"1998", "9", "2"},
      {"2000", "1", "1"},
      {"2004", "2", "28"},
      {"1937", "9", "8"},
      {"2017", "3", "1"},
  };
  assertEquals(answers.length, wrappers.length);

  for (int i = 0; i < wrappers.length; i++) {
    assertEquals(answers[i][0], localDates[i].getYear() + "");
    assertEquals(answers[i][1], localDates[i].getMonthOfYear() + "");
    assertEquals(answers[i][2], localDates[i].getDayOfMonth() + "");
    assertEquals(encodeAnswers[i], TiConstant.create(wrappers[i]).toProto().toString());
  }
}
 
Example 17
Source File: DateServiceConfig.java    From securing-rest-api-spring-security with Apache License 2.0 4 votes vote down vote up
@Bean
DateTimeZone defaultTimeZone() {
  return DateTimeZone.UTC;
}
 
Example 18
Source File: TestDetectionJobSchedulerUtils.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetNewEntriesForDSTBegins() throws Exception {

  DatasetConfigDTO datasetConfig = new DatasetConfigDTO();
  datasetConfig.setTimeColumn("Date");
  datasetConfig.setTimeUnit(TimeUnit.DAYS);
  datasetConfig.setTimeDuration(1);
  DateTimeZone dateTimeZone = DateTimeZone.UTC;

  AnomalyFunctionDTO anomalyFunction = new AnomalyFunctionDTO();

  // DST started on 2017031203
  DateTimeFormatter dateTimeFormatter = DetectionJobSchedulerUtils.
      getDateTimeFormatterForDataset(datasetConfig, dateTimeZone);
  String currentDateTimeString = "201703120437";
  String currentDateTimeStringRounded = "20170312";
  DateTime currentDateTime = minuteDateTimeFormatter.parseDateTime(currentDateTimeString);
  DateTime currentDateTimeRounded = dateTimeFormatter.parseDateTime(currentDateTimeStringRounded);
  DetectionStatusDTO lastEntryForFunction = null;

  // null last entry
  Map<String, Long> newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 1);
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));

  // last entry same as current time
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(currentDateTimeStringRounded);
  lastEntryForFunction.setDateToCheckInMS(currentDateTimeRounded.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 0);

  // last entry 1 day before current time, before DST
  String lastEntryDateTimeString = "20170311";
  DateTime lastEntryDateTime = dateTimeFormatter.parseDateTime(lastEntryDateTimeString);
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(lastEntryDateTimeString);
  lastEntryForFunction.setDateToCheckInMS(lastEntryDateTime.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 1);
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));

  // last entry 3 days before current time
  lastEntryDateTimeString = "20170309";
  lastEntryDateTime = dateTimeFormatter.parseDateTime(lastEntryDateTimeString);
  lastEntryForFunction = new DetectionStatusDTO();
  lastEntryForFunction.setDateToCheckInSDF(lastEntryDateTimeString);
  lastEntryForFunction.setDateToCheckInMS(lastEntryDateTime.getMillis());

  newEntries = DetectionJobSchedulerUtils.
      getNewEntries(currentDateTime, lastEntryForFunction, anomalyFunction, datasetConfig, dateTimeZone);
  Assert.assertEquals(newEntries.size(), 3);
  Assert.assertNotNull(newEntries.get("20170310"));
  Assert.assertNotNull(newEntries.get("20170311"));
  Assert.assertNotNull(newEntries.get("20170312"));
  Assert.assertEquals(newEntries.get(currentDateTimeStringRounded), new Long(currentDateTimeRounded.getMillis()));
}
 
Example 19
Source File: ValueFormatter.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public DateTime(String format, DateTimeZone timezone) {
    this.formatter = Joda.forPattern(format);
    this.timeZone = timezone != null ? timezone : DateTimeZone.UTC;
}
 
Example 20
Source File: BinlogStream.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private String dateToStringFromUTC(Long date) {
    DateTime dt = new DateTime(date, DateTimeZone.UTC);
    return dt.toString(DateUtil.DATE_PATTERN_ONLY_DATE);
}