Java 类org.joda.time.format.ISODateTimeFormat 实例源码

项目:exam    文件:ExamAPIController.java   
@SubjectNotPresent
public Result getActiveExams(Optional<String> date) {
    PathProperties pp = PathProperties.parse("(course(name, code, credits, " +
            "gradeScale(description, externalRef, displayName), organisation(code, name, nameAbbreviation)) " +
            "name, examActiveStartDate, examActiveEndDate, duration, enrollInstruction, examLanguages(code, name) " +
            "gradeScale(description, externalRef, displayName), examOwners(firstName, lastName, email), " +
            "examType(type)" +
            ")");
    DateTime dateTime = date.isPresent() ?
            ISODateTimeFormat.dateTimeParser().parseDateTime(date.get()) :
            DateTime.now();
    Query<Exam> query = Ebean.find(Exam.class);
    query.apply(pp);
    List<Exam> exams = query.where()
            .eq("state", Exam.State.PUBLISHED)
            .lt("examActiveStartDate", dateTime)
            .ge("examActiveEndDate", dateTime)
            .eq("executionType.type", ExamExecutionType.Type.PUBLIC.toString())
            .findList();

    return ok(exams, pp);
}
项目:exam    文件:ReservationAPIController.java   
@SubjectNotPresent
public Result getReservations(Optional<String> start, Optional<String> end, Optional<Long> roomId) {
    PathProperties pp = PathProperties.parse("(startAt, endAt, noShow, " +
            "user(firstName, lastName, email, userIdentifier), " +
            "enrolment(exam(name, examOwners(firstName, lastName, email), parent(examOwners(firstName, lastName, email)))), " +
            "machine(name, ipAddress, otherIdentifier, room(name, roomCode)))");
    Query<Reservation> query = Ebean.find(Reservation.class);
    pp.apply(query);
    ExpressionList<Reservation> el = query.where()
            .isNotNull("enrolment")
            .ne("enrolment.exam.state", Exam.State.DELETED);
    if (start.isPresent()) {
        DateTime startDate = ISODateTimeFormat.dateTimeParser().parseDateTime(start.get());
        el = el.ge("startAt", startDate.toDate());
    }

    if (end.isPresent()) {
        DateTime endDate = ISODateTimeFormat.dateTimeParser().parseDateTime(end.get());
        el = el.lt("endAt", endDate.toDate());
    }
    if (roomId.isPresent()) {
        el = el.eq("machine.room.id", roomId.get());
    }
    Set<Reservation> reservations = el.orderBy("startAt").findSet();
    return ok(reservations, pp);
}
项目:elasticsearch_my    文件:DateProcessor.java   
@Override
public void execute(IngestDocument ingestDocument) {
    String value = ingestDocument.getFieldValue(field, String.class);

    DateTime dateTime = null;
    Exception lastException = null;
    for (Function<String, DateTime> dateParser : dateParsers) {
        try {
            dateTime = dateParser.apply(value);
        } catch (Exception e) {
            //try the next parser and keep track of the exceptions
            lastException = ExceptionsHelper.useOrSuppress(lastException, e);
        }
    }

    if (dateTime == null) {
        throw new IllegalArgumentException("unable to parse date [" + value + "]", lastException);
    }

    ingestDocument.setFieldValue(targetField, ISODateTimeFormat.dateTime().print(dateTime));
}
项目:elasticsearch_my    文件:SearchQueryIT.java   
public void testDateRangeInQueryString() {
    //the mapping needs to be provided upfront otherwise we are not sure how many failures we get back
    //as with dynamic mappings some shards might be lacking behind and parse a different query
    assertAcked(prepareCreate("test").addMapping(
            "type", "past", "type=date", "future", "type=date"
    ));

    String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1));
    String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1));
    client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get();
    refresh();

    SearchResponse searchResponse = client().prepareSearch().setQuery(queryStringQuery("past:[now-2M/d TO now/d]")).get();
    assertHitCount(searchResponse, 1L);

    searchResponse = client().prepareSearch().setQuery(queryStringQuery("future:[now/d TO now+2M/d]")).get();
    assertHitCount(searchResponse, 1L);

    SearchPhaseExecutionException e = expectThrows(SearchPhaseExecutionException.class, () -> client().prepareSearch()
            .setQuery(queryStringQuery("future:[now/D TO now+2M/d]").lenient(false)).get());
    assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
    assertThat(e.toString(), containsString("unit [D] not supported for date math"));
}
项目:elasticsearch_my    文件:SearchQueryIT.java   
public void testDateRangeInQueryStringWithTimeZone_7880() {
    //the mapping needs to be provided upfront otherwise we are not sure how many failures we get back
    //as with dynamic mappings some shards might be lacking behind and parse a different query
    assertAcked(prepareCreate("test").addMapping(
            "type", "past", "type=date"
    ));

    DateTimeZone timeZone = randomDateTimeZone();
    String now = ISODateTimeFormat.dateTime().print(new DateTime(timeZone));
    logger.info(" --> Using time_zone [{}], now is [{}]", timeZone.getID(), now);
    client().prepareIndex("test", "type", "1").setSource("past", now).get();
    refresh();

    SearchResponse searchResponse = client().prepareSearch().setQuery(queryStringQuery("past:[now-1m/m TO now+1m/m]")
            .timeZone(timeZone.getID())).get();
    assertHitCount(searchResponse, 1L);
}
项目:elasticsearch_my    文件:SimpleValidateQueryIT.java   
public void testExplainDateRangeInQueryString() {
    assertAcked(prepareCreate("test").setSettings(Settings.builder()
            .put(indexSettings())
            .put("index.number_of_shards", 1)));

    String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1));
    String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1));

    client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get();

    refresh();

    ValidateQueryResponse response = client().admin().indices().prepareValidateQuery()
            .setQuery(queryStringQuery("past:[now-2M/d TO now/d]")).setRewrite(true).get();

    assertNoFailures(response);
    assertThat(response.getQueryExplanation().size(), equalTo(1));
    assertThat(response.getQueryExplanation().get(0).getError(), nullValue());
    DateTime twoMonthsAgo = new DateTime(DateTimeZone.UTC).minusMonths(2).withTimeAtStartOfDay();
    DateTime now = new DateTime(DateTimeZone.UTC).plusDays(1).withTimeAtStartOfDay().minusMillis(1);
    assertThat(response.getQueryExplanation().get(0).getExplanation(),
            equalTo("past:[" + twoMonthsAgo.getMillis() + " TO " + now.getMillis() + "]"));
    assertThat(response.isValid(), equalTo(true));
}
项目:elasticsearch_my    文件:BaseXContentTestCase.java   
public void testDate() throws Exception {
    assertResult("{'date':null}", () -> builder().startObject().field("date", (Date) null).endObject());
    assertResult("{'date':null}", () -> builder().startObject().field("date").value((Date) null).endObject());

    final Date d1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
    assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1", d1).endObject());
    assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1").value(d1).endObject());

    final Date d2 = new DateTime(2016, 12, 25, 7, 59, 42, 213, DateTimeZone.UTC).toDate();
    assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2", d2).endObject());
    assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2").value(d2).endObject());

    final DateTimeFormatter formatter = randomFrom(ISODateTimeFormat.basicDate(), ISODateTimeFormat.dateTimeNoMillis());
    final Date d3 = DateTime.now().toDate();

    String expected = "{'d3':'" + formatter.print(d3.getTime()) + "'}";
    assertResult(expected, () -> builder().startObject().field("d3", d3, formatter).endObject());
    assertResult(expected, () -> builder().startObject().field("d3").value(d3, formatter).endObject());

    expectNonNullFormatterException(() -> builder().startObject().field("d3", d3, null).endObject());
    expectNonNullFormatterException(() -> builder().startObject().field("d3").value(d3, null).endObject());
    expectNonNullFormatterException(() -> builder().value(null, 1L));
}
项目:flume-release-1.7.0    文件:TestBucketPath.java   
@Test
public void testDateRace() {
  Clock mockClock = mock(Clock.class);
  DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
  long two = parser.parseMillis("2013-04-21T02:59:59-00:00");
  long three = parser.parseMillis("2013-04-21T03:00:00-00:00");
  when(mockClock.currentTimeMillis()).thenReturn(two, three);

  // save & modify static state (yuck)
  Clock origClock = BucketPath.getClock();
  BucketPath.setClock(mockClock);

  String pat = "%H:%M";
  String escaped = BucketPath.escapeString(pat,
      new HashMap<String, String>(),
      TimeZone.getTimeZone("UTC"), true, Calendar.MINUTE, 10, true);

  // restore static state
  BucketPath.setClock(origClock);

  Assert.assertEquals("Race condition detected", "02:50", escaped);
}
项目:flume-release-1.7.0    文件:TestSyslogParser.java   
@Test
public void testRfc5424DateParsing() {
  final String[] examples = {
    "1985-04-12T23:20:50.52Z", "1985-04-12T19:20:50.52-04:00",
    "2003-10-11T22:14:15.003Z", "2003-08-24T05:14:15.000003-07:00",
    "2012-04-13T11:11:11-08:00", "2012-04-13T08:08:08.0001+00:00",
    "2012-04-13T08:08:08.251+00:00"
  };

  SyslogParser parser = new SyslogParser();
  DateTimeFormatter jodaParser = ISODateTimeFormat.dateTimeParser();

  for (String ex : examples) {
    Assert.assertEquals(
        "Problem parsing date string: " + ex,
        jodaParser.parseMillis(ex),
        parser.parseRfc5424Date(ex));
  }
}
项目:QDrill    文件:VectorOutput.java   
@Override
public void writeTimestamp(boolean isNull) throws IOException {
  TimeStampWriter ts = writer.timeStamp();
  if(!isNull){
    switch (parser.getCurrentToken()) {
    case VALUE_NUMBER_INT:
      DateTime dt = new DateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
      ts.writeTimeStamp(dt.getMillis());
      break;
    case VALUE_STRING:
      DateTimeFormatter f = ISODateTimeFormat.dateTime();
      ts.writeTimeStamp(DateTime.parse(parser.getValueAsString(), f).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
      break;
    default:
      throw UserException.unsupportedError()
          .message(parser.getCurrentToken().toString())
          .build(LOG);
    }
  }
}
项目:QDrill    文件:VectorOutput.java   
@Override
public void writeTimestamp(boolean isNull) throws IOException {
  TimeStampWriter ts = writer.timeStamp(fieldName);
  if(!isNull){
    switch (parser.getCurrentToken()) {
    case VALUE_NUMBER_INT:
      DateTime dt = new DateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
      ts.writeTimeStamp(dt.getMillis());
      break;
    case VALUE_STRING:
      DateTimeFormatter f = ISODateTimeFormat.dateTime();
      ts.writeTimeStamp(DateTime.parse(parser.getValueAsString(), f).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
      break;
    default:
      throw UserException.unsupportedError()
      .message(parser.getCurrentToken().toString())
      .build(LOG);
    }
  }
}
项目:QDrill    文件:BasicJsonOutput.java   
protected BasicJsonOutput(JsonGenerator gen, DateOutputFormat dateOutput) {
  Preconditions.checkNotNull(dateOutput);
  Preconditions.checkNotNull(gen);

  this.gen = gen;

  switch (dateOutput) {
  case SQL: {
    dateFormatter = DateUtility.formatDate;
    timeFormatter = DateUtility.formatTime;
    timestampFormatter = DateUtility.formatTimeStamp;
    break;
  }
  case ISO: {
    dateFormatter = ISODateTimeFormat.date();
    timeFormatter = ISODateTimeFormat.time();
    timestampFormatter = ISODateTimeFormat.dateTime();
    break;
  }

  default:
    throw new UnsupportedOperationException(String.format("Unable to support date output of type %s.", dateOutput));
  }
}
项目:stdds-monitor    文件:APIController.java   
@RequestMapping("/timeline-status")
public List<TimelineValue> timelineStatus(@RequestParam(value = "link") String link) {

    // formatter for use with json data
    DateTimeFormatter df = ISODateTimeFormat.dateTime().withZoneUTC();

    List<TimelineValue> timeline = new ArrayList<TimelineValue>();

    List<Notification> notificationList = notificationRepo.findByEventOrderByTime(link);
    extractChangeEvents(df, timeline, notificationList);

    List<Link> links = linkRepo.findByName(link);
    if (links != null && !links.isEmpty()) {
        Link l = links.get(0);
        List<Connection> connections = l.getConnections();

        for (Connection c : connections) {
            List<Notification> connNotList = notificationRepo.findByEventOrderByTime(c.getName());
            extractChangeEvents(df, timeline, connNotList);
        }
    }

    return timeline;
}
项目:exam    文件:ReservationAPIController.java   
@SubjectNotPresent
public Result getRoomOpeningHours(Long roomId, Optional<String> date) {
    if (!date.isPresent()) {
        return badRequest("no search date given");
    }
    LocalDate searchDate = ISODateTimeFormat.dateParser().parseLocalDate(date.get());
    PathProperties pp = PathProperties.parse("(*, defaultWorkingHours(*), calendarExceptionEvents(*))");
    Query<ExamRoom> query = Ebean.find(ExamRoom.class);
    pp.apply(query);
    ExamRoom room = query.where().idEq(roomId).findUnique();
    if (room == null) {
        return notFound("room not found");
    }
    room.setCalendarExceptionEvents(room.getCalendarExceptionEvents().stream().filter(ee -> {
        LocalDate start = new LocalDate(ee.getStartDate()).withDayOfMonth(1);
        LocalDate end = new LocalDate(ee.getEndDate()).dayOfMonth().withMaximumValue();
        return !start.isAfter(searchDate) && !end.isBefore(searchDate);

    }).collect(Collectors.toList()));
    return ok(room, pp);
}
项目:exam    文件:ReportController.java   
private <T> ExpressionList<T> applyFilters(ExpressionList<T> query, String deptFieldPrefix, String dateField,
                                           String dept, String start, String end) {
    ExpressionList<T> result = query;
    if (dept != null) {
        String[] depts = dept.split(",");
        result = result.in(String.format("%s.department", deptFieldPrefix), (Object[]) depts);
    }
    if (start != null) {
        DateTime startDate = DateTime.parse(start, ISODateTimeFormat.dateTimeParser());
        result = result.ge(dateField, startDate.toDate());
    }
    if (end != null) {
        DateTime endDate = DateTime.parse(end, ISODateTimeFormat.dateTimeParser()).plusDays(1);
        result = result.lt(dateField, endDate.toDate());
    }
    return result;
}
项目:exam    文件:CalendarControllerTest.java   
@Test
@RunAsStudent
public void testCreateReservationStartIsPast() throws Exception {
    // Setup
    DateTime start = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).minusHours(1);
    DateTime end = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).plusHours(2);

    // Execute
    Result result = request(Helpers.POST, "/app/calendar/reservation",
            Json.newObject().put("roomId", room.getId())
                    .put("examId", exam.getId())
                    .put("start", ISODateTimeFormat.dateTime().print(start))
                    .put("end", ISODateTimeFormat.dateTime().print(end)));
    assertThat(result.status()).isEqualTo(400);

    // Verify
    ExamEnrolment ee = Ebean.find(ExamEnrolment.class, enrolment.getId());
    assertThat(ee.getReservation()).isNull();
}
项目:exam    文件:CalendarControllerTest.java   
@Test
@RunAsStudent
public void testCreateReservationEndsBeforeStarts() throws Exception {
    // Setup
    DateTime start = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).plusHours(2);
    DateTime end = DateTime.now().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).plusHours(1);

    // Execute
    Result result = request(Helpers.POST, "/app/calendar/reservation",
            Json.newObject().put("roomId", room.getId())
                    .put("examId", exam.getId())
                    .put("start", ISODateTimeFormat.dateTime().print(start))
                    .put("end", ISODateTimeFormat.dateTime().print(end)));
    assertThat(result.status()).isEqualTo(400);

    // Verify
    ExamEnrolment ee = Ebean.find(ExamEnrolment.class, enrolment.getId());
    assertThat(ee.getReservation()).isNull();
}
项目:exam    文件:ExternalCalendarInterfaceTest.java   
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    ArrayNode an = Json.newArray();
    ObjectNode slot1 = Json.newObject();
    ObjectNode slot2 = Json.newObject();
    DateTime soon = DateTime.now().plusHours(1);
    slot1.put("start", ISODateTimeFormat.dateTime().print(soon));
    slot1.put("end", ISODateTimeFormat.dateTime().print(soon.plusHours(1)));
    slot1.put("availableMachines", 4);
    slot2.put("start", ISODateTimeFormat.dateTime().print(soon.plusHours(2)));
    slot2.put("end", ISODateTimeFormat.dateTime().print(soon.plusHours(3)));
    slot2.put("availableMachines", 7);
    an.add(slot1);
    an.add(slot2);
    RemoteServerHelper.writeJsonResponse(response, an, HttpServletResponse.SC_OK);
}
项目:dremio-oss    文件:VectorOutput.java   
@Override
public void writeTimestamp(boolean isNull) throws IOException {
  TimeStampMilliWriter ts = writer.timeStampMilli();
  if(!isNull){
    switch (parser.getCurrentToken()) {
    case VALUE_NUMBER_INT:
      LocalDateTime dt = new LocalDateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(dt));
      break;
    case VALUE_STRING:
      DateTimeFormatter f = ISODateTimeFormat.dateTime();
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(LocalDateTime.parse(parser.getValueAsString(), f)));
      break;
    default:
      throw UserException.unsupportedError()
          .message(parser.getCurrentToken().toString())
          .build(LOG);
    }
  }
}
项目:dremio-oss    文件:VectorOutput.java   
@Override
public void writeTimestamp(boolean isNull) throws IOException {
  TimeStampMilliWriter ts = writer.timeStampMilli(fieldName);
  if(!isNull){
    switch (parser.getCurrentToken()) {
    case VALUE_NUMBER_INT:
      LocalDateTime dt = new LocalDateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(dt));
      break;
    case VALUE_STRING:
      DateTimeFormatter f = ISODateTimeFormat.dateTime().withZoneUTC();
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(LocalDateTime.parse(parser.getValueAsString(), f)));
      break;
    default:
      throw UserException.unsupportedError()
      .message(parser.getCurrentToken().toString())
      .build(LOG);
    }
  }
}
项目:dremio-oss    文件:BasicJsonOutput.java   
protected BasicJsonOutput(JsonGenerator gen, DateOutputFormat dateOutput) {
  Preconditions.checkNotNull(dateOutput);
  Preconditions.checkNotNull(gen);

  this.gen = gen;

  switch (dateOutput) {
  case SQL: {
    dateFormatter = DateUtility.formatDate.withZoneUTC();
    timeFormatter = DateUtility.formatTime.withZoneUTC();
    timestampFormatter = DateUtility.formatTimeStampMilli.withZoneUTC();
    break;
  }
  case ISO: {
    dateFormatter = ISODateTimeFormat.date().withZoneUTC();
    timeFormatter = ISODateTimeFormat.time().withZoneUTC();
    timestampFormatter = ISODateTimeFormat.dateTime().withZoneUTC();
    break;
  }

  default:
    throw new UnsupportedOperationException(String.format("Unable to support date output of type %s.", dateOutput));
  }
}
项目:dremio-oss    文件:FragmentHandler.java   
void checkStateAndLogIfNecessary() {
  if (!fragmentStarted) {
    final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    if (isCancelled()) {
      logger.warn("Received cancel request at {} for fragment {} that was never started",
        formatter.print(cancellationTime),
        QueryIdHelper.getQueryIdentifier(handle));
    }

    FragmentEvent event;
    while ((event = finishedReceivers.poll()) != null) {
      logger.warn("Received early fragment termination at {} for path {} {} -> {} for a fragment that was never started",
        formatter.print(event.time),
        QueryIdHelper.getQueryId(handle.getQueryId()),
        QueryIdHelper.getFragmentId(event.handle),
        QueryIdHelper.getFragmentId(handle)
      );
    }
  }
}
项目:elasticsearch_my    文件:ExplainActionIT.java   
public void testExplainDateRangeInQueryString() {
    createIndex("test");

    String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1));
    String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1));

    client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get();

    refresh();

    ExplainResponse explainResponse = client().prepareExplain("test", "type", "1").setQuery(queryStringQuery("past:[now-2M/d TO now/d]")).get();
    assertThat(explainResponse.isExists(), equalTo(true));
    assertThat(explainResponse.isMatch(), equalTo(true));
}
项目:elasticsearch_my    文件:SimpleJodaTests.java   
public void testUpperBound() {
    MutableDateTime dateTime = new MutableDateTime(3000, 12, 31, 23, 59, 59, 999, DateTimeZone.UTC);
    DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);

    String value = "2000-01-01";
    int i = formatter.parseInto(dateTime, value, 0);
    assertThat(i, equalTo(value.length()));
    assertThat(dateTime.toString(), equalTo("2000-01-01T23:59:59.999Z"));
}
项目:elasticsearch_my    文件:SimpleJodaTests.java   
public void testIsoDateFormatDateOptionalTimeUTC() {
    DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
    long millis = formatter.parseMillis("1970-01-01T00:00:00Z");
    assertThat(millis, equalTo(0L));
    millis = formatter.parseMillis("1970-01-01T00:00:00.001Z");
    assertThat(millis, equalTo(1L));
    millis = formatter.parseMillis("1970-01-01T00:00:00.1Z");
    assertThat(millis, equalTo(100L));
    millis = formatter.parseMillis("1970-01-01T00:00:00.1");
    assertThat(millis, equalTo(100L));
    millis = formatter.parseMillis("1970-01-01T00:00:00");
    assertThat(millis, equalTo(0L));
    millis = formatter.parseMillis("1970-01-01");
    assertThat(millis, equalTo(0L));

    millis = formatter.parseMillis("1970");
    assertThat(millis, equalTo(0L));

    try {
        formatter.parseMillis("1970 kuku");
        fail("formatting should fail");
    } catch (IllegalArgumentException e) {
        // all is well
    }

    // test offset in format
    millis = formatter.parseMillis("1970-01-01T00:00:00-02:00");
    assertThat(millis, equalTo(TimeValue.timeValueHours(2).millis()));
}
项目:elasticsearch_my    文件:SimpleJodaTests.java   
public void testIsoVsCustom() {
    DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
    long millis = formatter.parseMillis("1970-01-01T00:00:00");
    assertThat(millis, equalTo(0L));

    formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").withZone(DateTimeZone.UTC);
    millis = formatter.parseMillis("1970/01/01 00:00:00");
    assertThat(millis, equalTo(0L));

    FormatDateTimeFormatter formatter2 = Joda.forPattern("yyyy/MM/dd HH:mm:ss");
    millis = formatter2.parser().parseMillis("1970/01/01 00:00:00");
    assertThat(millis, equalTo(0L));
}
项目:schedule-dataflow-appengine    文件:DataFlowUtils.java   
public static Pair<JobStatus,String> isJobRunning(DataflowPipelineOptions options, String jobName, int jobIntervalinMinutes) throws IOException {
    DataflowClient dataflowClient = DataflowClient.create(options);
    ListJobsResponse currentJobs = dataflowClient.listJobs(null);
    final List<Job> jobs = currentJobs.getJobs();
    if (jobs!=null) {
        List<Job> runningJobs = jobs.stream()
                .filter(job -> job.getName().startsWith(jobName))
                .filter(job -> job.getCurrentState().equals("JOB_STATE_RUNNING"))
                .collect(Collectors.toList());
        //check if x minutes have passed sine last run
        if (runningJobs.size() == 0) {
            Optional<Job> job_state_done = jobs.stream()
                    .filter(job -> job.getName().startsWith(jobName))
                    .filter(job -> job.getCurrentState().equals("JOB_STATE_DONE"))
                    .max(Comparator.comparingLong(p -> ISODateTimeFormat.dateTimeParser().parseDateTime(p.getCreateTime()).getMillis()));
            if (job_state_done.isPresent()) {
                long millis = ISODateTimeFormat.dateTimeParser().parseDateTime(job_state_done.get().getCreateTime()).getMillis();
                long passedMinutes = (System.currentTimeMillis() - millis) / 1000 / 60;
                if (passedMinutes < jobIntervalinMinutes)
                    return Pair.of(JobStatus.QuitePeriod,job_state_done.get().getCreateTime());
                else
                    return Pair.of(JobStatus.Nothing,"");
            }

        } else
            return Pair.of(JobStatus.Running,runningJobs.get(0).getCreateTime());
    }
    return Pair.of(JobStatus.Nothing,"");
}
项目:lemon    文件:AdvancedBusinessCalendar.java   
/**
 * 解析结束时间.
 */
@Override
public Date resolveEndDate(String endDateString) {
    return ISODateTimeFormat
            .dateTimeParser()
            .withZone(
                    DateTimeZone.forTimeZone(clockReader
                            .getCurrentTimeZone()))
            .parseDateTime(endDateString).toCalendar(null).getTime();
}
项目:lams    文件:DateTimeFormatterFactory.java   
/**
 * Create a new {@code DateTimeFormatter} using this factory.
 * <p>If no specific pattern or style has been defined,
 * the supplied {@code fallbackFormatter} will be used.
 * @param fallbackFormatter the fall-back formatter to use when no specific
 * factory properties have been set (can be {@code null}).
 * @return a new date time formatter
 */
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
    DateTimeFormatter dateTimeFormatter = null;
    if (StringUtils.hasLength(this.pattern)) {
        dateTimeFormatter = DateTimeFormat.forPattern(this.pattern);
    }
    else if (this.iso != null && this.iso != ISO.NONE) {
        switch (this.iso) {
            case DATE:
                dateTimeFormatter = ISODateTimeFormat.date();
                break;
            case TIME:
                dateTimeFormatter = ISODateTimeFormat.time();
                break;
            case DATE_TIME:
                dateTimeFormatter = ISODateTimeFormat.dateTime();
                break;
            case NONE:
                /* no-op */
                break;
            default:
                throw new IllegalStateException("Unsupported ISO format: " + this.iso);
        }
    }
    else if (StringUtils.hasLength(this.style)) {
        dateTimeFormatter = DateTimeFormat.forStyle(this.style);
    }

    if (dateTimeFormatter != null && this.timeZone != null) {
        dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
    }
    return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
项目:lams    文件:AssertionMarshaller.java   
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {

    Assertion assertion = (Assertion) samlElement;

    if (assertion.getID() != null) {
        domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID());
        if (assertion.getMinorVersion() != 0) {
            domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true);
        }
    }

    if (assertion.getIssuer() != null) {
        domElement.setAttributeNS(null, Assertion.ISSUER_ATTRIB_NAME, assertion.getIssuer());
    }

    if (assertion.getIssueInstant() != null) {
        String date = ISODateTimeFormat.dateTime().print(assertion.getIssueInstant());
        domElement.setAttributeNS(null, Assertion.ISSUEINSTANT_ATTRIB_NAME, date);
    }

    domElement.setAttributeNS(null, Assertion.MAJORVERSION_ATTRIB_NAME, "1");
    if (assertion.getMinorVersion() == 0) {
        domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "0");
    } else {
        domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "1");
    }
}
项目:QDrill    文件:VectorOutput.java   
@Override
public void writeTime(boolean isNull) throws IOException {
  TimeWriter t = writer.time();
  if(!isNull){
    DateTimeFormatter f = ISODateTimeFormat.time();
    t.writeTime((int) ((f.parseDateTime(parser.getValueAsString())).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
  }
}
项目:QDrill    文件:VectorOutput.java   
@Override
public void writeTime(boolean isNull) throws IOException {
  TimeWriter t = writer.time(fieldName);
  if(!isNull){
    DateTimeFormatter f = ISODateTimeFormat.time();
    t.writeTime((int) ((f.parseDateTime(parser.getValueAsString())).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
  }
}
项目:alfresco-remote-api    文件:AbstractCalendarWebScript.java   
/**
 * Removes the time zone for a given date if the Calendar Entry is an all day event
 * 
 * @return ISO 8601 formatted date String if datePattern is null
 */
protected String removeTimeZoneIfRequired(Date date, Boolean isAllDay, Boolean removeTimezone, String datePattern)
{
    if (removeTimezone)
    {
        DateTime dateTime = new DateTime(date, DateTimeZone.UTC);

        if (null == datePattern)
        {
            return dateTime.toString((isAllDay) ? (ALL_DAY_DATETIME_FORMATTER) : (ISODateTimeFormat.dateTime()));
        }
        else
        {
            // For Legacy Dates and Times.
            return dateTime.toString(DateTimeFormat.forPattern(datePattern));
        }
    }

    // This is for all other cases, including the case, when UTC time zone is configured

    if (!isAllDay && (null == datePattern))
    {
        return ISO8601DateFormat.format(date);
    }

    DateFormat simpleDateFormat = new SimpleDateFormat((null != datePattern) ? (datePattern) : (ALL_DAY_DATETIME_PATTERN));

    return simpleDateFormat.format(date);
}
项目:spring-boot-sms-zenvia    文件:JsonHelper.java   
public Gson getGson() {
    Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>(){
                @Override
                public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
                }
            })
            .create();
    return gson;
}
项目:exam    文件:CalendarReservationSanitizer.java   
private Http.Request sanitize(Http.Context ctx, JsonNode body) throws SanitizingException {
    Http.Request request = SanitizingHelper.sanitize("roomId", body, Long.class, Attrs.ROOM_ID, ctx.request());
    request = SanitizingHelper.sanitize("examId", body, Long.class, Attrs.EXAM_ID, request);

    // Custom sanitizing ->

    // Optional AIDS (sic!)
    Collection<Integer> aids = new HashSet<>();
    if (body.has("aids")) {
        Iterator<JsonNode> it = body.get("aids").elements();
        while (it.hasNext()) {
            aids.add(it.next().asInt());
        }
    }
    request = request.addAttr(Attrs.ACCESSABILITES, aids);

    // Mandatory start + end dates
    if (body.has("start") && body.has("end")) {
        DateTime start = DateTime.parse(body.get("start").asText(), ISODateTimeFormat.dateTimeParser());
        DateTime end = DateTime.parse(body.get("end").asText(), ISODateTimeFormat.dateTimeParser());
        if (start.isBeforeNow() || end.isBefore(start)) {
            throw new SanitizingException("invalid dates");
        }
        request = request.addAttr(Attrs.START_DATE, start);
        request = request.addAttr(Attrs.END_DATE, end);
    } else {
        throw new SanitizingException("invalid dates");
    }
    return request;
}
项目:exam    文件:ExaminationDateSanitizer.java   
private Http.Request sanitize(Http.Context ctx, JsonNode body) throws SanitizingException {
    if (body.has("date")) {
        LocalDate date = LocalDate.parse(body.get("date").asText(), ISODateTimeFormat.dateTimeParser());
        return ctx.request().addAttr(Attrs.DATE, date);
    } else {
        throw new SanitizingException("no date");
    }
}
项目:exam    文件:ExamRecordAPIController.java   
private static List<ExamScore> getScores(String startDate) {
    DateTime start = ISODateTimeFormat.dateTimeParser().parseDateTime(startDate);
    List<ExamRecord> examRecords = Ebean.find(ExamRecord.class)
            .fetch("examScore")
            .where()
            .gt("timeStamp", start.toDate())
            .findList();
    return examRecords.stream().map(ExamRecord::getExamScore).collect(Collectors.toList());
}
项目:exam    文件:CalendarController.java   
public TimeSlot(Interval interval, int machineCount, String exam) {
    start = ISODateTimeFormat.dateTime().print(interval.getStart());
    end = ISODateTimeFormat.dateTime().print(interval.getEnd());
    availableMachines = machineCount;
    ownReservation = machineCount < 0;
    conflictingExam = exam;
}