Java Code Examples for org.joda.time.DateTime#parse()

The following examples show how to use org.joda.time.DateTime#parse() . These examples are extracted from open source projects. 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
@Test
public void testSuccess_singleEvent_afterRecurrenceEnd_outsideAutorenewGracePeriod()
    throws Exception {
  // The domain creation date is 1999-01-05, and the first renewal date is thus 2000-01-05.
  DateTime testTime = DateTime.parse("2001-02-06T00:00:00Z");
  clock.setTo(testTime);
  recurring = persistResource(recurring.asBuilder()
      // The domain deletion date is 2000-04-05, which is not within the 45 day autorenew grace
      // period from the renewal date.
      .setRecurrenceEndTime(DateTime.parse("2000-04-05T00:00:00Z"))
      .setEventTime(domain.getCreationTime().plusYears(1))
      .build());
  action.cursorTimeParam = Optional.of(START_OF_TIME);
  runMapreduce();
  HistoryEntry persistedEntry = getOnlyHistoryEntryOfType(domain, DOMAIN_AUTORENEW);
  assertHistoryEntryMatches(
      domain, persistedEntry, "TheRegistrar", DateTime.parse("2000-02-19T00:00:00Z"), true);
  BillingEvent.OneTime expected = defaultOneTimeBuilder()
      .setBillingTime(DateTime.parse("2000-02-19T00:00:00Z"))
      .setParent(persistedEntry)
      .setSyntheticCreationTime(testTime)
      .build();
  assertBillingEventsForResource(domain, recurring, expected);
  assertCursorAt(testTime);
}
 
Example 2
public S3EventNotificationRecord(String awsRegion, String eventName, String eventSource, String eventTime,
                                 String eventVersion, RequestParametersEntity requestParameters,
                                 ResponseElementsEntity responseElements, S3Entity s3,
                                 UserIdentityEntity userIdentity) {
    this.awsRegion = awsRegion;
    this.eventName = eventName;
    this.eventSource = eventSource;

    if (eventTime != null)
    {
        this.eventTime = DateTime.parse(eventTime);
    }

    this.eventVersion = eventVersion;
    this.requestParameters = requestParameters;
    this.responseElements = responseElements;
    this.s3 = s3;
    this.userIdentity = userIdentity;
}
 
Example 3
private static BasicQueryInfo createQueryInfo(String queryId, QueryState state)
{
    return new BasicQueryInfo(
            new QueryId(queryId),
            TEST_SESSION.toSessionRepresentation(),
            Optional.of(new ResourceGroupId("global")),
            state,
            GENERAL_POOL,
            true,
            URI.create("1"),
            "",
            Optional.empty(),
            Optional.empty(),
            new BasicQueryStats(
                    DateTime.parse("1991-09-06T05:00-05:30"),
                    DateTime.parse("1991-09-06T05:01-05:30"),
                    Duration.valueOf("8m"),
                    Duration.valueOf("7m"),
                    Duration.valueOf("34m"),
                    13,
                    14,
                    15,
                    100,
                    DataSize.valueOf("21GB"),
                    22,
                    23,
                    DataSize.valueOf("23GB"),
                    DataSize.valueOf("24GB"),
                    DataSize.valueOf("25GB"),
                    DataSize.valueOf("26GB"),
                    Duration.valueOf("23m"),
                    Duration.valueOf("24m"),
                    true,
                    ImmutableSet.of(WAITING_FOR_MEMORY),
                    OptionalDouble.of(20)),
            null,
            null);
}
 
Example 4
Source Project: nomulus   File: RdeUploadActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRunWithLock_failsAfterThreeAttempts() throws Exception {
  int port = sftpd.serve("user", "password", folder.getRoot());
  URI uploadUrl = URI.create(String.format("sftp://user:[email protected]:%d/", port));
  DateTime stagingCursor = DateTime.parse("2010-10-18TZ");
  DateTime uploadCursor = DateTime.parse("2010-10-17TZ");
  persistResource(Cursor.create(RDE_STAGING, stagingCursor, Registry.get("tld")));
  RdeUploadAction action = createAction(uploadUrl);
  action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 3));
  RuntimeException thrown =
      assertThrows(RuntimeException.class, () -> action.runWithLock(uploadCursor));
  assertThat(thrown).hasMessageThat().contains("The crow flies in square circles.");
}
 
Example 5
@Test
public void testGetLastDeterminedTestDateTime() throws ParseException {
    pattern = "1969-12-31T19:00:00z";
    DateTime date = DateTime.parse(pattern);
    assertEquals("Input time pattern is yyyy-MM-dd'T'H:m:sZ ",millisecondsOfDateWithoutOffset,ls5424pb.toDate("",pattern));
    assertEquals("Making sure toDate sets the right value ",date,ls5424pb.getLastDeterminedDateTime());
}
 
Example 6
@Test
public void testInsertSameEdOrgAfterDate() {
    cacheObject.addEntry(testEntity, testEdOrg, testExpirationDate);
    DateTime expDate = DateTime.parse("2011-07-30", FMT);
    cacheObject.addEntry(testEntity, testEdOrg, expDate);

    Map<String, DateTime> result = cacheObject.getEntriesById(testEntity);

    Assert.assertEquals(1, result.size());
    Assert.assertTrue(result.keySet().contains(testEdOrg));
    Assert.assertEquals(expDate, result.get(testEdOrg));
}
 
Example 7
Source Project: liteflow   File: TaskVersionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过任务版本获取对应的时间
 * @param version
 * @param timeUnit
 * @return
 */
public static Date getDateByVersion(String version, TimeUnit timeUnit){

    String versionExpression = timeUnit.getVersionExpression();
    DateTimeFormatter format = DateTimeFormat.forPattern(versionExpression);
    DateTime dateTime = DateTime.parse(version, format);
    return dateTime.toDate();

}
 
Example 8
public void validatePostUploadRequest(final String signature, final String metadata, final String timeout, final String hostname, final long contentLength, final String
        uuid) throws
        InvalidParameterValueException {
    // check none of the params are empty
    if (StringUtils.isEmpty(signature) || StringUtils.isEmpty(metadata) || StringUtils.isEmpty(timeout)) {
        updateStateMapWithError(uuid, "signature, metadata and expires are compulsory fields.");
        throw new InvalidParameterValueException("signature, metadata and expires are compulsory fields.");
    }

    //check that contentLength exists and is greater than zero
    if (contentLength <= 0) {
        throw new InvalidParameterValueException("content length is not set in the request or has invalid value.");
    }

    //validate signature
    final String fullUrl = "https://" + hostname + "/upload/" + uuid;
    final String computedSignature = EncryptionUtil.generateSignature(metadata + fullUrl + timeout, getPostUploadPSK());
    final boolean isSignatureValid = computedSignature.equals(signature);
    if (!isSignatureValid) {
        updateStateMapWithError(uuid, "signature validation failed.");
        throw new InvalidParameterValueException("signature validation failed.");
    }

    //validate timeout
    final DateTime timeoutDateTime = DateTime.parse(timeout, ISODateTimeFormat.dateTime());
    if (timeoutDateTime.isBeforeNow()) {
        updateStateMapWithError(uuid, "request not valid anymore.");
        throw new InvalidParameterValueException("request not valid anymore.");
    }
}
 
Example 9
Source Project: nomulus   File: EppLifecycleDomainTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDomainCreation_failsBeforeSunrise() throws Exception {
  DateTime sunriseDate = DateTime.parse("2000-05-30T00:00:00Z");
  createTld(
      "example",
      new ImmutableSortedMap.Builder<DateTime, TldState>(Ordering.natural())
          .put(START_OF_TIME, PREDELEGATION)
          .put(sunriseDate, START_DATE_SUNRISE)
          .put(sunriseDate.plusMonths(2), GENERAL_AVAILABILITY)
          .build());

  assertThatLoginSucceeds("NewRegistrar", "foo-BAR2");

  createContactsAndHosts();

  assertThatCommand("domain_create_sunrise_encoded_mark.xml")
      .atTime(sunriseDate.minusDays(1))
      .hasResponse(
          "response_error.xml",
          ImmutableMap.of(
              "CODE", "2002",
              "MSG", "The current registry phase does not allow for general registrations"));

  assertThatCommand("domain_info_testvalidate.xml")
      .atTime(sunriseDate.plusDays(1))
      .hasResponse(
          "response_error.xml",
          ImmutableMap.of(
              "CODE", "2303",
              "MSG", "The domain with given ID (test-validate.example) doesn't exist."));

  assertThatLogoutSucceeds();
}
 
Example 10
Source Project: nomulus   File: TimeOfYearTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_getInstancesOfTimeOfYearInRange_empty() {
  DateTime startDate = DateTime.parse("2012-05-01T00:00:00Z");
  DateTime endDate = DateTime.parse("2013-02-01T00:00:00Z");
  TimeOfYear timeOfYear = TimeOfYear.fromDateTime(DateTime.parse("2012-03-01T00:00:00Z"));
  assertThat(timeOfYear.getInstancesInRange(Range.closed(startDate, endDate))).isEmpty();
}
 
Example 11
private String formatDateTimeToUTC(String originalTime) {
    DateTime dateTime = DateTime.parse(originalTime);

    // TODO: Remove workaround for Java SDK bug not returning time in UTC.
    try {
        dateTime = dateTime.toDateTime(DateTimeZone.UTC);
    } catch(Exception ex) {
        // Swallow exception and use date as-is.
    }

    return dateTime.toString(DATE_FORMAT_STRING);
}
 
Example 12
public DeviceServiceModel(final Device device, final TwinServiceModel twin, String iotHubHostName,
                          boolean isConnectedEdgeDevice) {
    this(device.geteTag(),
         device.getDeviceId(),
         device.getCloudToDeviceMessageCount(),
         device.getLastActivityTime() == null ? null : DateTime.parse(device.getLastActivityTime(), ISODateTimeFormat.dateTimeParser().withZoneUTC()),
         isConnectedEdgeDevice || device.getConnectionState() == DeviceConnectionState.Connected,
         device.getStatus() == DeviceStatus.Enabled,
         device.getCapabilities() != null ? device.getCapabilities().isIotEdge() : twin.getIsEdgeDevice(),
         device.getStatusUpdatedTime() == null ? null : DateTime.parse(device.getStatusUpdatedTime(), ISODateTimeFormat.dateTimeParser().withZoneUTC()),
         twin,
         new AuthenticationMechanismServiceModel(device),
         iotHubHostName);
}
 
Example 13
Source Project: api-snippets   File: list-get-example-3.7.x.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
  Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

  DateTime dateTime = DateTime.parse("2009-07-06");

  ResourceSet<Call> calls =
      Call.reader().setStatus(Call.Status.COMPLETED).setStartTime(Range.atLeast(dateTime)).read();

  // Loop over calls and print out a property for each one.
  for (Call call : calls) {
    System.out.println(call.getTo());
  }
}
 
Example 14
Source Project: activitystreams   File: Adapters.java    License: Apache License 2.0 4 votes vote down vote up
public DateTime apply(String v) {
  return DateTime.parse(v);
}
 
Example 15
@Test
public void jsonPage() throws ServletException {

    User user = CmsTestUtils.createAuthenticatedUser("jsonPage");
    Site site = CmsTestUtils.createSite(user, "jsonPage");
    Page page1 = CmsTestUtils.createPage(site, "jsonPage1");
    Page page2 = CmsTestUtils.createPage(site, "jsonPage2");
    Page page3 = CmsTestUtils.createPage(site, "jsonPage3");
    page2.addComponents(new ListCategoryPosts(CmsTestUtils.createCategory(site, "jsonPage")));
    page3.addComponents(new StaticPost(CmsTestUtils.createPost(site, "jsonPage")));
    page3.addComponents(new StaticPost(CmsTestUtils.createPost(site, "jsonPage22")));
    page3.addComponents(new ListCategoryPosts(CmsTestUtils.createCategory(site, "jsonPage22Cate")));
    page3.addComponents(Component.forType(ViewPost.class));

    JsonObject siteJson = new SiteExporter(site).export(site);
    assertTrue(siteJson.has("pages"));
    assertTrue(siteJson.get("pages").isJsonArray());
    assertTrue(siteJson.get("pages").getAsJsonArray().size() == site.getPagesSet().size());
    List<String> sitePagesSlugs = site.getPagesSet().stream().map(Page::getSlug).collect(toList());
    for (JsonElement pageEl : siteJson.get("pages").getAsJsonArray()) {
        assertTrue(sitePagesSlugs.contains(pageEl.getAsString()));
    }

    for (Page page : site.getPagesSet()) {
        JsonObject pageJson = new SiteExporter(site).export(page);

        assertTrue(pageJson.has("slug"));
        assertEquals(pageJson.get("slug").getAsString(), page.getSlug());

        assertTrue(pageJson.has("name"));
        assertEquals(LocalizedString.fromJson(pageJson.get("name")), page.getName());

        assertTrue(pageJson.has("site"));
        assertEquals(pageJson.get("site").getAsString(), page.getSite().getSlug());

        assertTrue(pageJson.has("canViewGroup"));
        assertEquals(Group.parse(pageJson.get("canViewGroup").getAsString()), page.getCanViewGroup());

        assertTrue(pageJson.has("published"));
        assertEquals(pageJson.get("published").getAsBoolean(), page.getPublished());

        assertTrue(pageJson.has("createdBy"));
        assertEquals(User.findByUsername(pageJson.get("createdBy").getAsString()), page.getCreatedBy());

        assertTrue(pageJson.has("creationDate"));
        DateTime creationDate = DateTime.parse(pageJson.get("creationDate").getAsString());
        assertTrue(equalDates(creationDate, page.getCreationDate()));

        assertTrue(pageJson.has("modificationDate"));
        DateTime modificationDate = DateTime.parse(pageJson.get("modificationDate").getAsString());
        assertTrue(equalDates(modificationDate, page.getModificationDate()));


        assertTrue(pageJson.has("menuItems"));
        assertTrue(pageJson.get("menuItems").isJsonArray());
        List<String> menuItemsIds = page.getMenuItemsSet().stream().map(MenuItem::getExternalId).collect(toList());
        assertEquals(pageJson.get("menuItems").getAsJsonArray().size(), page.getMenuItemsSet().size());
        for (JsonElement menuItemEl : pageJson.get("menuItems").getAsJsonArray()) {
            assertTrue(menuItemEl.isJsonPrimitive());
            assertTrue(menuItemsIds.contains(menuItemEl.getAsString()));
        }

        assertTrue(pageJson.has("components"));
        assertTrue(pageJson.get("components").isJsonArray());
        assertEquals(pageJson.get("components").getAsJsonArray().size(), page.getComponentsSet().size());
        List<String> pageComponentSlugs = page.getComponentsSet().stream().map(Component::getType).collect(toList());
        for (JsonElement componentEl : pageJson.get("components").getAsJsonArray()) {
            assertTrue(componentEl.isJsonObject());
            JsonObject componentJson = componentEl.getAsJsonObject();

            assertTrue(componentJson.has("type"));
            assertTrue(componentJson.get("type").isJsonPrimitive());
            assertTrue(pageComponentSlugs.contains(componentJson.get("type").getAsString()));

            ComponentDescriptor type = Component.forType(componentJson.get("type").getAsString());
            assertNotNull(type);
            if (!type.isStateless()) {
                assertTrue(componentJson.has("site"));
                assertEquals(componentJson.get("site").getAsString(), page.getSite().getSlug());

                assertTrue(componentJson.has("page"));
                assertEquals(componentJson.get("page").getAsString(), page.getSlug());
            }
        }
    }
}
 
Example 16
@Override
public DateTime deserialize(JsonParser jsonparser, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {
  String date = jsonparser.getText();
  return DateTime.parse(date);
}
 
Example 17
Source Project: rya   File: TemporalTupleSet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public CloseableIteration<Statement, QueryEvaluationException> performSearch(final String searchTerms,
        final StatementConstraints contraints) throws QueryEvaluationException {
    final TemporalInstant queryInstant = new TemporalInstantRfc3339(DateTime.parse(searchTerms));
    return temporalIndexer.queryInstantAfterInstant(queryInstant, contraints);
}
 
Example 18
Source Project: nomulus   File: DateTimeUtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSuccess_leapSafeAddYears() {
  DateTime startDate = DateTime.parse("2012-02-29T00:00:00Z");
  assertThat(startDate.plusYears(4)).isEqualTo(DateTime.parse("2016-02-29T00:00:00Z"));
  assertThat(leapSafeAddYears(startDate, 4)).isEqualTo(DateTime.parse("2016-02-28T00:00:00Z"));
}
 
Example 19
Source Project: spork   File: AccumuloBinaryConverter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * NOT IMPLEMENTED
 */
@Override
public DateTime bytesToDateTime(byte[] b) throws IOException {
    String s = new String(b, Constants.UTF8);
    return DateTime.parse(s);
}
 
Example 20
Source Project: nomulus   File: ListTldsActionTest.java    License: Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
  createTld("xn--q9jyb4c");
  action = new ListTldsAction();
  action.clock = new FakeClock(DateTime.parse("2000-01-01TZ"));
}