コード例 #1
0
 @Test
 public void testStudentListCourses() {
   DateTime created1 = getDate(2010, 1, 1);
   DateTime modified1 = getDate(2010, 1, 1);
   DateTime beginDate1 = getDate(2010, 2, 2);
   DateTime endDate1 = getDate(2010, 3, 3);
   DateTime enrolmentTimeEnd1 = getDate(2010, 1, 1);
   given()
       .headers(getAuthHeaders())
       .get("/students/students/{ID}/courses", TEST_STUDENT_ID)
       .then()
       .body("id.size()", is(1))
       .body("id[0]", is(1000))
       .body("name[0]", is("Test Course #1"))
       .body("courseNumber[0]", is(1))
       .body("created[0]", is(created1.toString()))
       .body("lastModified[0]", is(modified1.toString()))
       .body("beginDate[0]", is(beginDate1.toString()))
       .body("endDate[0]", is(endDate1.toString()))
       .body("enrolmentTimeEnd[0]", is(enrolmentTimeEnd1.toString()))
       .body("description[0]", is("Course #1 for testing"))
       .body("length[0]", is(1.0f))
       .body("lengthUnitId[0]", is(1))
       .body("creatorId[0]", is(1))
       .body("lastModifierId[0]", is(1))
       .body("subjectId[0]", is(1))
       .body("maxParticipantCount[0]", is(100))
       .body("archived[0]", is(false));
 }
コード例 #2
0
  @Override
  public String getGerritQuery(ServerVersion serverVersion) {
    String operator = getOperator();

    if ("<=".equals(operator) || "<".equals(operator)) {
      return BeforeSearch._getGerritQuery(this, serverVersion);
    } else if (">=".equals(operator) || ">".equals(operator)) {
      return AfterSearch._getGerritQuery(this, serverVersion);
    }

    if (serverVersion != null
        && serverVersion.isFeatureSupported(ServerVersion.VERSION_BEFORE_SEARCH)
        && mDateTime != null) {
      // Use a combination of before and after to get an interval
      DateTime now = new DateTime();
      if (mPeriod == null) {
        mPeriod = new Period(mDateTime, now);
      }
      DateTime earlier = now.minus(adjust(mPeriod, +1));
      DateTime later = now.minus(mPeriod);

      SearchKeyword newer = new AfterSearch(earlier.toString(sGerritFormat));
      SearchKeyword older = new BeforeSearch(later.toString(sGerritFormat));
      return newer.getGerritQuery(serverVersion) + "+" + older.getGerritQuery(serverVersion);
    } else {
      // Need to leave off the operator and make sure we are using relative format
      /* Gerrit only supports specifying one time unit, so we will normalize the period
       *  into days.  */
      return OP_NAME + ":" + String.valueOf(toDays()) + "d";
    }
  }
コード例 #3
0
  /** 检查营业执照修改情况 */
  private void checkBusinessLicense(
      Map<String, String> changedInfo, PaperworkDto updatedPaperwork, PaperworkDto oldPaperwork) {

    if (!Objects.equal(updatedPaperwork.getBusinessLicense(), oldPaperwork.getBusinessLicense())) {
      changedInfo.put(
          ChangedInfoKeys.companyBusinessLicense(), updatedPaperwork.getBusinessLicense());
    }
    if (!Objects.equal(
        updatedPaperwork.getBusinessLicenseId(), oldPaperwork.getBusinessLicenseId())) {
      changedInfo.put(
          ChangedInfoKeys.companyBusinessLicenseId(), updatedPaperwork.getBusinessLicenseId());
    }

    DateTime updatedBlDate = new DateTime(updatedPaperwork.getBlDate());
    if (oldPaperwork.getBlDate() == null) {
      changedInfo.put(
          ChangedInfoKeys.companyBusinessLicenseDate(), updatedBlDate.toString(FORMATTER));
    } else {
      DateTime oldBlDate = new DateTime(oldPaperwork.getBlDate());
      if (!updatedBlDate.isEqual(oldBlDate)) {
        changedInfo.put(
            ChangedInfoKeys.companyBusinessLicenseDate(), updatedBlDate.toString(FORMATTER));
      }
    }
  }
コード例 #4
0
ファイル: JodaDemo.java プロジェクト: twq0621/herbert-utils
  public static void testTimeZone() {

    System.out.println("演示时区");

    String format = "yyyy-MM-dd HH:mm:ss zZZ";

    // DateTime的毫秒即System的毫秒,即1970到现在的UTC的毫秒数.
    System.out.println(new DateTime().getMillis() + " " + System.currentTimeMillis());

    // 将日期按默认时区打印
    DateTime fooDate = new DateTime(1978, 6, 1, 12, 10, 8, 0);
    System.out.println(
        fooDate.toString(format) + " " + fooDate.getMillis()); // "1978-06-01 12:10:08"

    // 将日期按UTC时区打印
    DateTime zoneWithUTC = fooDate.withZone(DateTimeZone.UTC);
    System.out.println(
        zoneWithUTC.toString(format)
            + " "
            + zoneWithUTC.getMillis()); // "1978-06-01 04:10:08", sameMills

    // 按不同的时区分析字符串,得到不同的时间
    String dateString = "1978-06-01 12:10:08";
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    DateTime parserResult1 =
        fmt.withZone(DateTimeZone.forID("US/Pacific")).parseDateTime(dateString);
    DateTime parserResult2 = fmt.withZone(DateTimeZone.UTC).parseDateTime(dateString);

    System.out.println(parserResult1.toString(format) + " " + parserResult1.getMillis());
    System.out.println(parserResult2.toString(format) + " " + parserResult2.getMillis());
  }
コード例 #5
0
  /**
   * @param isNullable isNullable
   * @param earliest lower boundary date
   * @param latest upper boundary date
   * @param onlyBusinessDays only business days
   * @return a list of boundary dates
   */
  public List<String> positiveCase(
      boolean isNullable, String earliest, String latest, boolean onlyBusinessDays) {
    List<String> values = new LinkedList<>();

    if (earliest.equalsIgnoreCase(latest)) {
      values.add(earliest);
      if (isNullable) {
        values.add("");
      }
      return values;
    }

    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);

    String earlyDay = parser.print(earlyDate);
    String nextDay = getNextDay(earlyDate.toString().substring(0, 10), onlyBusinessDays);
    String prevDay = getPreviousDay(lateDate.toString().substring(0, 10), onlyBusinessDays);
    String lateDay = parser.print(lateDate);

    values.add(earlyDay);
    values.add(nextDay);
    values.add(prevDay);
    values.add(lateDay);

    if (isNullable) {
      values.add("");
    }
    return values;
  }
コード例 #6
0
  /**
   * Grab random holiday from the equivalence class that falls between the two dates
   *
   * @param earliest the earliest date parameter as defined in the model
   * @param latest the latest date parameter as defined in the model
   * @return a holiday that falls between the dates
   */
  public String getRandomHoliday(String earliest, String latest) {
    String dateString = "";
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);
    List<Holiday> holidays = new LinkedList<>();

    int min = Integer.parseInt(earlyDate.toString().substring(0, 4));
    int max = Integer.parseInt(lateDate.toString().substring(0, 4));
    int range = max - min + 1;
    int randomYear = (int) (Math.random() * range) + min;

    for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {
      holidays.add(s);
    }
    Collections.shuffle(holidays);

    for (Holiday holiday : holidays) {
      dateString = convertToReadableDate(holiday.forYear(randomYear));
      if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {
        break;
      }
    }
    return dateString;
  }
コード例 #7
0
 public static Map<String, Double> constructDatePlaceHolderForDouble(
     final DateTime startDate, final DateTime endDate, final String pattern) {
   final Map<String, Double> currentYearTillDays = new LinkedHashMap<String, Double>();
   for (DateTime date = startDate; date.isBefore(endDate); date = date.plusDays(1))
     currentYearTillDays.put(date.toString(pattern), Double.valueOf(0));
   currentYearTillDays.put(endDate.toString(pattern), Double.valueOf(0));
   return currentYearTillDays;
 }
コード例 #8
0
 @Override
 public String toString() {
   return "NewToDoItemWithDeadlineCreatedEvent("
       + todoId
       + ", '"
       + description
       + "' before "
       + deadline.toString("dd-MM-YYYY")
       + " at "
       + deadline.toString("HH:mm")
       + ")";
 }
コード例 #9
0
 public static Integer batchInsertData(
     List<Object[]> data, Connection countCon, PreparedStatement ps, Set<String> yearMonthCache)
     throws SQLException {
   if (CollectionUtils.isEmpty(data)) {
     return 0;
   }
   Integer curMaxId = 0;
   for (int i = 0; i < data.size(); i++) {
     // 插入数据
     // 数据库表的设定也不允许任何列为空
     if (data.get(i).length < 4
         || data.get(i)[1] == null
         || data.get(i)[2] == null
         || data.get(i)[3] == null
         || data.get(i)[0] == null) {
       logger.error("搜索关键字备份 - 数据插入:存在空值!");
       continue;
     }
     Integer curId = ((BigInteger) data.get(i)[0]).intValue();
     Date curDate = (Date) data.get(i)[3];
     String curYearMonth = new DateTime(curDate).toString("yyyyMM");
     if (!yearMonthCache.contains(curYearMonth)) {
       yearMonthCache.add(curYearMonth);
       // 如果当前id大于等于5月最大id,结束
       for (DateTime temp = DateTime.parse("201401", DateTimeFormat.forPattern("yyyyMM"));
           temp.toString("yyyyMM").compareTo(curYearMonth) < 0;
           temp = temp.plusMonths(1)) { // 如果出现比现在的月份还小的分区不存在的情况,也创建
         String tempCurString = temp.toString("yyyyMM");
         if (!yearMonthCache.contains(tempCurString)) {
           yearMonthCache.add(tempCurString);
           createMonthPartitionIfNotExist(tempCurString, countCon);
         }
       }
       createMonthPartitionIfNotExist(curYearMonth, countCon);
     }
     ps.setObject(1, curId);
     ps.setObject(2, data.get(i)[1]);
     ps.setObject(3, data.get(i)[2]);
     ps.setObject(4, curDate);
     ps.addBatch();
     if (curId > curMaxId) {
       curMaxId = curId;
     }
     if ((i + 1) == data.size()) {
       long b = new Date().getTime();
       ps.executeBatch();
       ps.clearBatch();
       logger.info("插入【" + data.size() + "】条数据,耗时【" + (new Date().getTime() - b) + "】毫秒");
     }
   }
   return curMaxId;
 }
コード例 #10
0
  @Test
  public void add_weeks_to_date_in_java_with_joda() {

    DateTime xmas = new DateTime(2012, 12, 25, 0, 0, 0, 0);
    DateTime newYearsDay = xmas.plusWeeks(1);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss z");

    logger.info(xmas.toString(fmt));
    logger.info(newYearsDay.toString(fmt));

    assertTrue(newYearsDay.isAfter(xmas));
  }
コード例 #11
0
 @Test
 public void shouldValidateValidCallLogRecord() {
   DateTime now = ISODateTimeUtil.nowInTimeZoneUTC();
   DateTime tenMinutesAddedToNow = now.plusMinutes(10);
   CallLogRecord callLogRecord =
       new CallLogRecord(
           UUID.randomUUID(),
           1,
           CallLogRecordType.LESSON.name(),
           now.toString(),
           tenMinutesAddedToNow.toString());
   List<ValidationError> validationErrors = callLogRecord.validate();
   assertThat(validationErrors.size(), Is.is(0));
 }
コード例 #12
0
ファイル: Timer.java プロジェクト: OldDragon2A/Timer
  public Element toXML() {
    Element result = new Element("timer");

    XMLUtil.createElement("title", getTitle(), result);
    XMLUtil.createElement("started", started == null ? "" : started.toString(), result);
    XMLUtil.createElement("total", period.toString(), result);
    XMLUtil.createElement("speed", update_speed, result);

    XMLUtil.createElement("x", getX(), result);
    XMLUtil.createElement("y", getY(), result);
    XMLUtil.createElement("width", getWidth(), result);
    XMLUtil.createElement("height", getHeight(), result);

    XMLUtil.createElement(
        "foreground", String.format("%08x", total.getForeground().getRGB()), result);
    XMLUtil.createElement(
        "background", String.format("%08x", panel.getBackground().getRGB()), result);

    XMLUtil.createElement("visible", isVisible(), result);

    Element times = new Element("times");
    for (TimeSpan ts : this.times) {
      times.addContent(ts.toXML());
    }
    result.addContent(times);
    return result;
  }
コード例 #13
0
ファイル: CloudStackPuller.java プロジェクト: T-NOVA/cyclops
  /**
   * Will determine when was the last entry point (pull from CloudStack), or even if there was any
   *
   * @return date object of the last commit, or epoch if there was none
   */
  private DateTime whenWasLastPull() {
    DateTime last = new InfluxDBClient().getLastPull();
    logger.trace("Getting the last pull date " + last.toString());

    // get date specified by admin
    String date = settings.getCloudStackImportFrom();
    if (date != null && !date.isEmpty()) {
      try {
        logger.trace("Admin provided us with import date preference " + date);
        DateTime selection = Time.getDateForTime(date);

        // if we are first time starting and having Epoch, change it to admin's selection
        // otherwise skip admin's selection and continue from the last DB entry time
        if (last.getMillis() == 0) {
          logger.debug("Setting first import date as configuration file dictates.");
          last = selection;
        }
      } catch (Exception ignored) {
        // ignoring configuration preference, as admin didn't provide correct format
        logger.debug("Import date selection for CloudStack ignored - use yyyy-MM-dd format");
      }
    }

    return last;
  }
コード例 #14
0
  @Test
  public void testTimerStartDateISO() throws Exception {

    byte[] content =
        IoUtils.readBytesFromInputStream(
            this.getClass().getResourceAsStream("/BPMN2-TimerStartDate.bpmn2"));
    String processContent = new String(content, "UTF-8");

    DateTime now = new DateTime(System.currentTimeMillis());
    now = now.plus(2000);

    processContent = processContent.replaceFirst("#\\{date\\}", now.toString());
    Resource resource = ResourceFactory.newReaderResource(new StringReader(processContent));
    resource.setSourcePath("/BPMN2-TimerStartDate.bpmn2");
    resource.setTargetPath("/BPMN2-TimerStartDate.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(resource);

    ksession = createKnowledgeSession(kbase);
    final List<Long> list = new ArrayList<Long>();
    ksession.addEventListener(
        new DefaultProcessEventListener() {
          public void afterProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
          }
        });
    assertEquals(0, list.size());
    Thread.sleep(3000);
    assertEquals(1, list.size());
  }
コード例 #15
0
ファイル: Ead2002Exporter.java プロジェクト: EHRI/ehri-rest
 private void addProfileDesc(XMLStreamWriter sw, Description desc) {
   tag(
       sw,
       "profiledesc",
       () -> {
         tag(
             sw,
             "creation",
             () -> {
               characters(sw, resourceAsString("export-boilerplate.txt"));
               DateTime now = DateTime.now();
               tag(sw, "date", now.toString(), attrs("normal", unitDateNormalFormat.print(now)));
             });
         tag(
             sw,
             "langusage",
             () ->
                 tag(
                     sw,
                     "language",
                     LanguageHelpers.codeToName(desc.getLanguageOfDescription()),
                     attrs("langcode", desc.getLanguageOfDescription())));
         Optional.ofNullable(desc.<String>getProperty(IsadG.rulesAndConventions))
             .ifPresent(value -> tag(sw, "descrules", value, attrs("encodinganalog", "3.7.2")));
       });
 }
コード例 #16
0
ファイル: Common.java プロジェクト: avi-kr/budly-customer
  public static String formatUTCToLocal(String datetime) {
    String returnTimeDate = "";
    DateTime dtUTC = null;
    DateTimeZone timezone = DateTimeZone.getDefault();
    DateTimeFormatter formatDT = DateTimeFormat.forPattern("MMM dd, yyyy  hh:mma");

    try {
      DateTime dateDateTime1 = formatDT.parseDateTime(datetime);
      DateTime now = new DateTime();
      DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC);
      long instant = now.getMillis();
      long instantUTC = nowUTC.getMillis();
      long offset = instantUTC - instant;

      // convert to local time
      dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC);
      // dtUTC = dateDateTime1.toDateTime(timezone);
      dtUTC = dtUTC.plusMillis((int) offset);

      returnTimeDate = dtUTC.toString(formatDT);
    } catch (Exception e) {
      returnTimeDate = "null";
      e.printStackTrace();
    }
    return returnTimeDate;
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the ReconciliationReportService.
    ReconciliationReportServiceInterface reconciliationReportService =
        dfpServices.get(session, ReconciliationReportServiceInterface.class);

    // Get the first day of last month.
    DateTime lastMonth = new DateTime().minusMonths(1).dayOfMonth().withMinimumValue();

    // Create a statement to select the last month's reconciliation report.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("startDate = :startDate")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("startDate", lastMonth.toString("YYYY-MM-dd"));

    // Get the reconciliation report.
    ReconciliationReportPage page =
        reconciliationReportService.getReconciliationReportsByStatement(
            statementBuilder.toStatement());

    ReconciliationReport reconciliationReport =
        Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    System.out.printf(
        "Reconciliation report with ID \"%d\" for month %s/%s was found.%n",
        reconciliationReport.getId(),
        reconciliationReport.getStartDate().getMonth(),
        reconciliationReport.getStartDate().getYear());
  }
コード例 #18
0
  /**
   * Prints out information about the operating environment. This includes the operating system
   * name, version and architecture, the JDK version, available CPU cores, memory currently used by
   * the JVM process, the maximum amount of memory that may be used by the JVM, and the current time
   * in UTC.
   *
   * @param out output writer to which information will be written
   */
  protected void printOperatingEnvironmentInformation(PrintWriter out) {
    Runtime runtime = Runtime.getRuntime();
    DateTime now = new DateTime(ISOChronology.getInstanceUTC());

    out.println("### Operating Environment Information");
    out.println("operating_system: " + System.getProperty("os.name"));
    out.println("operating_system_version: " + System.getProperty("os.version"));
    out.println("operating_system_architecture: " + System.getProperty("os.arch"));
    out.println("jdk_version: " + System.getProperty("java.version"));
    out.println("available_cores: " + runtime.availableProcessors());
    out.println("used_memory: " + runtime.totalMemory() / 1048576 + "MB");
    out.println("maximum_memory: " + runtime.maxMemory() / 1048576 + "MB");
    out.println("start_time: " + startTime.toString(dateFormat));
    out.println("current_time: " + now.toString(dateFormat));
    out.println("uptime: " + (now.getMillis() - startTime.getMillis()) + "ms");
  }
コード例 #19
0
  // IMPLEMENTATION
  @Override
  public void validate(final ValidationContext ctx) {
    final Date value = ValidationUtils.getDate(getValue(ctx));

    if (value != null) {
      final DateTime date = new DateTime(value);

      addParam(MessageSubstitutor.VALUE, date.toString());
      addParam("type", type);

      // lower
      if (lowerBoundary != null) {
        final DateTime lower = getDateLimit(false);
        if (date.isBefore(lower)) {
          ctx.getStatus().error(this);
        }
      }

      // upper
      if (upperBoundary != null) {
        final DateTime upper = getDateLimit(true);
        if (date.isAfter(upper)) {
          ctx.getStatus().error(this);
        }
      }
    }
  }
コード例 #20
0
  /**
   * Creates a new Google Calendar Entry for each <code>item</code> and adds it to the processing
   * queue. The entries' title will either be the items name or <code>alias</code> if it is <code>
   * != null</code>.
   *
   * <p>The new Calendar Entry will contain a single command to be executed e.g.<br>
   *
   * <p><code>send &lt;item.name&gt; &lt;item.state&gt;</code>
   *
   * @param item the item which state should be persisted.
   * @param alias the alias under which the item should be persisted.
   */
  @Override
  public void store(final Item item, final String alias) {
    if (initialized) {
      String newAlias = alias != null ? alias : item.getName();

      CalendarEventEntry myEntry = new CalendarEventEntry();
      myEntry.setTitle(new PlainTextConstruct("[PresenceSimulation] " + newAlias));
      myEntry.setContent(
          new PlainTextConstruct(
              String.format(executeScript, item.getName(), item.getState().toString())));

      DateTime nowPlusOffset = new DateTime().plusDays(offset);

      com.google.gdata.data.DateTime time =
          com.google.gdata.data.DateTime.parseDateTime(nowPlusOffset.toString());
      When eventTimes = new When();
      eventTimes.setStartTime(time);
      eventTimes.setEndTime(time);
      myEntry.addTime(eventTimes);

      entries.offer(myEntry);

      logger.trace(
          "added new entry '{}' for item '{}' to upload queue",
          myEntry.getTitle().getPlainText(),
          item.getName());
    } else {
      logger.debug(
          "GCal PresenceSimulation Service isn't initialized properly! No entries will be uploaded to your Google Calendar");
    }
  }
コード例 #21
0
ファイル: RoughTime.java プロジェクト: trejkaz/TimeFlow
  public String toString() {
    if (isDefined()) {
      return dateTime.toString();
    }

    return "unknown";
  }
コード例 #22
0
 private Date getDateFromDateTime(DateTime dateTime) {
   try {
     return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
         .parse(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
   } catch (ParseException e) {
     return null;
   }
 }
コード例 #23
0
  @Test
  @UseWithField(field = "boundaryDatesMode", valuesFrom = FROM_ENUM, value = "")
  @Templates("plain")
  public void testBoundaryDatesMode() {
    calendarAttributes.set(CalendarAttributes.boundaryDatesMode, boundaryDatesMode.value);
    DayPicker dayPicker = popupCalendar.openPopup().getDayPicker();
    MetamerPage.waitRequest(popupCalendar, WaitRequestType.XHR).setDateTime(firstOfNovember2012);
    PopupFooterControls footerControls = popupCalendar.openPopup().getFooterControls();
    HeaderControls headerControls = popupCalendar.openPopup().getHeaderControls();
    DateTime yearAndMonth;
    String firstOfNovember2012String = firstOfNovember2012.toString(dateTimeFormatter);
    switch (boundaryDatesMode) {
      case INACTIVE:
      case NULL:
        try {
          MetamerPage.waitRequest(dayPicker.getBoundaryDays().get(0), WaitRequestType.NONE)
              .select();
          fail("Item should not be selected.");
        } catch (TimeoutException ex) { // ok
        }
        // apply and check, that the date has not changed
        footerControls = popupCalendar.openPopup().getFooterControls();
        MetamerPage.waitRequest(footerControls, WaitRequestType.NONE).applyDate();
        assertEquals(popupCalendar.getInput().getStringValue(), firstOfNovember2012String);
        break;
      case SCROLL:
        // scroll to 28th of October 2012
        try {
          MetamerPage.waitRequest(dayPicker.getBoundaryDays().get(0), WaitRequestType.NONE)
              .select();
          fail("Item should not be selected.");
        } catch (TimeoutException ex) { // ok
        }
        yearAndMonth = headerControls.getYearAndMonth();
        assertEquals(yearAndMonth.getYear(), 2012);
        assertEquals(yearAndMonth.getMonthOfYear(), 10);
        // apply and check, that the date has not changed
        footerControls = popupCalendar.openPopup().getFooterControls();
        MetamerPage.waitRequest(footerControls, WaitRequestType.NONE).applyDate();
        assertEquals(popupCalendar.getInput().getStringValue(), firstOfNovember2012String);
        break;
      case SELECT:
        // select 28th of October 2012
        CalendarDay day = dayPicker.getBoundaryDays().get(0);
        MetamerPage.waitRequest(day.getDayElement(), WaitRequestType.NONE).click();
        yearAndMonth = headerControls.getYearAndMonth();
        assertEquals(yearAndMonth.getYear(), 2012);
        assertEquals(yearAndMonth.getMonthOfYear(), 10);

        MetamerPage.waitRequest(footerControls, WaitRequestType.XHR).applyDate();
        DateTime parsedDateTime =
            dateTimeFormatter.parseDateTime(popupCalendar.getInput().getStringValue());
        assertEquals(parsedDateTime.getYear(), 2012);
        assertEquals(parsedDateTime.getMonthOfYear(), 10);
        assertEquals(parsedDateTime.getDayOfMonth(), 28);
        break;
    }
  }
コード例 #24
0
  private void appendCommonElements(
      Element element,
      Content content,
      DateTime originalPublicationDate,
      String lastModified,
      String applicationSpecificData,
      Iterable<String> genres,
      Element instances) {

    if (!Strings.isNullOrEmpty(content.getDescription())) {
      element.appendChild(stringElement("Description", LAKEVIEW, content.getDescription()));
    }

    if (applicationSpecificData != null) {
      element.appendChild(
          stringElement("ApplicationSpecificData", LAKEVIEW, applicationSpecificData));
    }

    element.appendChild(stringElement("LastModifiedDate", LAKEVIEW, lastModified));
    element.appendChild(stringElement("ApplicableLocale", LAKEVIEW, LOCALE));

    if (content instanceof Brand && content.getImage() != null) {

      Element imageElem = createElement("Image", LAKEVIEW);
      imageElem.appendChild(stringElement("ImagePurpose", LAKEVIEW, "BoxArt"));
      imageElem.appendChild(stringElement("Url", LAKEVIEW, content.getImage()));

      Element imagesElement = createElement("Images", LAKEVIEW);
      imagesElement.appendChild(imageElem);
      element.appendChild(imagesElement);
    }

    if (!Iterables.isEmpty(genres)) {
      Element genresElem = createElement("Genres", LAKEVIEW);
      for (String genre : genres) {
        if (genre.startsWith("http://www.channel4.com")) {
          genresElem.appendChild(stringElement("Genre", LAKEVIEW, C4GenreTitles.title(genre)));
        }
      }
      element.appendChild(genresElem);
    }

    Element pc = createElement("ParentalControl", LAKEVIEW);
    pc.appendChild(stringElement("HasGuidance", LAKEVIEW, String.valueOf(true)));
    element.appendChild(pc);
    element.appendChild(
        stringElement("PublicWebUri", LAKEVIEW, String.format("%s.atom", webUriRoot(content))));

    if (instances != null) {
      element.appendChild(instances);
    }

    element.appendChild(
        stringElement(
            "OriginalPublicationDate",
            LAKEVIEW,
            originalPublicationDate.toString(DATETIME_FORMAT)));
  }
コード例 #25
0
  @Test
  public void datePickerTest() throws Exception {
    // Using Joda Time DateTime and DateTimeFormatter for this test!
    // Creating test data - using +3 days, hours and minutes
    // to make sure that all wheels are used
    DateTime testDate = new DateTime().plusDays(3).plusHours(3).plusMinutes(3);

    // hour of the day - short format
    // i tried to get it using .hourOfDay().getAsShortText() but it would only return 24hr format...
    DateTimeFormatter hourOfDayFormat = DateTimeFormat.forPattern("K");

    // half day of day - AM or PM
    // have to use a new formatter for this as there is no getter - let me know if I'm wrong!
    DateTimeFormatter halfDayFormat = DateTimeFormat.forPattern("aa");

    // short date - example "Sun Dec 27"
    // to be used with the date picker in gregorian calendar
    DateTimeFormatter shortDateFormat = DateTimeFormat.forPattern("E MMM d");

    // longDate - example pattern "Dec 27, 2015, 5:55 PM"
    // to be used for assertion at the end of the test
    DateTimeFormatter longDateFormat = DateTimeFormat.forPattern("MMM d, yyyy, K:mm aa");

    final String hour = testDate.toString(hourOfDayFormat);
    final String minute = testDate.minuteOfHour().getAsString();
    final String shortDate = testDate.toString(shortDateFormat);
    final String longDate = testDate.toString(longDateFormat);
    final String halfDay = testDate.toString(halfDayFormat);

    driver.findElement(MobileBy.AccessibilityId("date_picker_button")).click();
    // wait for Date Picker view to load
    wait.until(
        ExpectedConditions.visibilityOf(driver.findElement(MobileBy.className("UIAPickerWheel"))));

    List<WebElement> pickerWheel_elements =
        driver.findElements(MobileBy.className("UIAPickerWheel"));
    pickerWheel_elements.get(0).sendKeys(shortDate);
    pickerWheel_elements.get(1).sendKeys(hour);
    pickerWheel_elements.get(2).sendKeys(minute);
    pickerWheel_elements.get(3).sendKeys(halfDay);

    String dateValidation_element =
        driver.findElement(MobileBy.AccessibilityId("current_date")).getText();
    assertThat(dateValidation_element, is(longDate));
  }
コード例 #26
0
  public String toString() {

    String output = "";
    output = "\nSpot ID: " + Integer.toString(SpotId);
    output += "\nCreation Time: " + CreatedOnUTC.toString();
    output += "\nBuoy Name: " + buoyName;
    output += "\nBuoy ID: " + buoyID;
    output += "\nObservation Date Time: " + obsvtnDateTime.toString();
    output += "\nLatitude: " + lat + " -90 to 90 (S to N)";
    output += "\nLongitude: " + lng + " -180 to 180 (W to E)";
    output += "\nWave Height: " + waveHeight + " ft";
    output += "\nDominant Wave Period: " + wavePerDom + " sec";
    output += "\nAverage Wave Period: " + wavePerAve + " sec";
    output += "\nWave Direction: " + waveDirection + " degrees";
    output += "\nWater Temp: " + waterTemp + " degrees F ('merica!)";

    return output;
  }
コード例 #27
0
  /**
   * Takes a date, and retrieves the next business day
   *
   * @param dateString the date
   * @param onlyBusinessDays only business days
   * @return a string containing the next business day
   */
  public String getNextDay(String dateString, boolean onlyBusinessDays) {
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime date = parser.parseDateTime(dateString).plusDays(1);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date.toDate());

    if (onlyBusinessDays) {
      if (cal.get(Calendar.DAY_OF_WEEK) == 1
          || cal.get(Calendar.DAY_OF_WEEK) == 7
          || isHoliday(date.toString().substring(0, 10))) {
        return getNextDay(date.toString().substring(0, 10), true);
      } else {
        return parser.print(date);
      }
    } else {
      return parser.print(date);
    }
  }
コード例 #28
0
  protected Map<String, String> addCustomDerivedQualifications(
      Map<String, String> qualificiation, DateTime asOfDate, boolean activeOnly) {
    Map<String, String> qual = new HashMap<String, String>();
    qual.putAll(qualificiation);
    qual.put("asOfDate", asOfDate.toString());
    qual.put("activeOnly", Boolean.toString(activeOnly));

    return qual;
  }
コード例 #29
0
 @Override
 public void initCustomMessages() {
   DateTimeFormatter dtf = DateTimeFormat.forPattern("MMM d, yyyy HH:mm");
   messageCases.put(
       MESSAGE_PAST_NAME,
       new ValidationMessageCase(
           MESSAGE_PAST_NAME,
           messagePast,
           setPastCorrectButton,
           setPastWrongButton,
           pastOutput,
           "Jan 2, 1980 12:00",
           DateInputValidationBean.PAST_VALUE_DEFAULT.toString(dtf),
           Sets.newHashSet(DateInputValidationBean.PAST_VALIDATION_MSG)));
   messageCases.put(
       MESSAGE_FUTURE_NAME,
       new ValidationMessageCase(
           MESSAGE_FUTURE_NAME,
           messageFuture,
           setFutureCorrectButton,
           setFutureWrongButton,
           futureOutput,
           "Jan 2, 3000 12:00",
           DateInputValidationBean.FUTURE_VALUE_DEFAULT.toString(dtf),
           Sets.newHashSet(DateInputValidationBean.FUTURE_VALIDATION_MSG)));
   DateTime lastYear =
       new DateTime(DateTimeZone.UTC)
           .minusYears(1)
           .withMonthOfYear(1)
           .withDayOfMonth(2)
           .withHourOfDay(12)
           .withMinuteOfHour(0)
           .withSecondOfMinute(0);
   messageCases.put(
       MESSAGE_LAST_YEAR_NAME,
       new ValidationMessageCase(
           MESSAGE_LAST_YEAR_NAME,
           messageLastYear,
           setLastYearCorrectButton,
           setLastYearWrongButton,
           lastYearOutput,
           lastYear.toString(dtf),
           DateInputValidationBean.LAST_YEAR_VALUE_DEFAULT.toString(dtf),
           Sets.newHashSet(DateInputValidationBean.LAST_YEAR_VALIDATION_MSG)));
   messageCases.put(
       MESSAGE_REQUIRED_NAME,
       new ValidationMessageCase(
           MESSAGE_REQUIRED_NAME,
           messageRequired,
           setRequiredCorrectButton,
           setRequiredWrongButton,
           requiredOutput,
           "Jan 2, 1980 12:00",
           DateInputValidationBean.REQUIRED_VALUE_DEFAULT.toString(dtf),
           Sets.newHashSet(DateInputValidationBean.REQUIRED_VALIDATION_MSG)));
 }
コード例 #30
0
ファイル: ReportUtilsTest.java プロジェクト: raymond301/swift
 @Test(dataProvider = "dates")
 public void shouldParseDates(final String input, final String output) {
   try {
     final DateTime date = ReportUtils.parseDate(input, "start");
     Assert.assertEquals(date.toString("MM-dd-yyyy HH:mm:ss"), output);
   } catch (Exception e) {
     Assert.assertEquals(
         MprcException.getDetailedMessage(e), output, "Exception message does not match");
   }
 }