private void testStartProcess(RuntimeEngine runtime) throws Exception {

    synchronized (
        (SingleSessionCommandService)
            ((CommandBasedStatefulKnowledgeSession) runtime.getKieSession()).getRunner()) {
      UserTransaction ut =
          (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
      try {
        ut.begin();
        logger.debug("Starting process on ksession {}", runtime.getKieSession().getIdentifier());
        Map<String, Object> params = new HashMap<String, Object>();
        DateTime now = new DateTime();
        now.plus(1000);

        params.put("x", "R2/" + wait + "/PT1S");
        ProcessInstance processInstance =
            runtime.getKieSession().startProcess("IntermediateCatchEvent", params);
        logger.debug(
            "Started process instance {} on ksession {}",
            processInstance.getId(),
            runtime.getKieSession().getIdentifier());
        ut.commit();
      } catch (Exception ex) {
        ut.rollback();
        throw ex;
      }
    }
  }
  @Test
  public void testWithConversion() throws IOException {

    DateTime today = new DateTime();

    Map<String, Object> resultMap =
        (Map<String, Object>)
            ControllerUtil.sendAndReceive(
                controller,
                "remoteProviderSimple",
                "method14",
                a(
                    ISODateTimeFormat.dateTime().print(today),
                    "normalParameter",
                    ISODateTimeFormat.date().print(today),
                    "99.9%"),
                Map.class);

    assertThat(resultMap.get("endDate")).isEqualTo(today.getMillis());
    ObjectMapper mapper = new ObjectMapper();

    List<Object> expectedValue =
        mapper.readValue(mapper.writeValueAsString(today.toLocalDate()), List.class);
    Object actualValue = resultMap.get("jodaLocalDate");

    assertThat((List<Object>) resultMap.get("jodaLocalDate")).isEqualTo(expectedValue);
    assertThat(resultMap.get("percent")).isEqualTo(0.999);
    assertThat(resultMap.get("normalParameter")).isEqualTo("normalParameter");
    assertThat(resultMap.get("remoteAddr")).isEqualTo("127.0.0.1");
  }
示例#3
0
  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    final EntityBase that = (EntityBase) o;
    if (id != null ? !id.equals(that.id) : that.id != null) {
      return false;
    }
    if (createdDate != null
        ? createdDate.compareTo(that.createdDate) != 0
        : that.createdDate != null) {
      return false;
    }
    if (updatedDate != null
        ? updatedDate.compareTo(that.updatedDate) != 0
        : that.updatedDate != null) {
      return false;
    }

    return true;
  }
    private static VesselTrackInfo getTrackInfo(Table TrackInfo_Table, String IMO_str)
        throws IOException {
      Get get = new Get(Bytes.toBytes(IMO_str));
      get.addColumn(details, lastlocation);
      get.addColumn(details, firstrecordtime);
      get.addColumn(details, lastrecordtime);

      Result result = TrackInfo_Table.get(get);

      byte[] last_location = result.getValue(details, lastlocation);
      byte[] fist_recordtime = result.getValue(details, firstrecordtime);
      byte[] last_recordtime = result.getValue(details, lastrecordtime);

      VesselTrackInfo trackinfo = new VesselTrackInfo();
      trackinfo.LastLocation = last_location;

      if (fist_recordtime != null) {
        trackinfo.FirstRecordTime =
            DateTime.parse(Bytes.toString(fist_recordtime), rawformatter).getMillis();
      }

      if (last_recordtime != null) {
        trackinfo.LastRecordTime =
            DateTime.parse(Bytes.toString(last_recordtime), rawformatter).getMillis();
      }

      return trackinfo;
    }
示例#5
0
 @Override
 public DateMidnight deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   // We'll accept either long (timestamp) or array:
   if (jp.isExpectedStartArrayToken()) {
     jp.nextToken(); // VALUE_NUMBER_INT
     int year = jp.getIntValue();
     jp.nextToken(); // VALUE_NUMBER_INT
     int month = jp.getIntValue();
     jp.nextToken(); // VALUE_NUMBER_INT
     int day = jp.getIntValue();
     if (jp.nextToken() != JsonToken.END_ARRAY) {
       throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after DateMidnight ints");
     }
     return new DateMidnight(year, month, day);
   }
   switch (jp.getCurrentToken()) {
     case VALUE_NUMBER_INT:
       return new DateMidnight(jp.getLongValue());
     case VALUE_STRING:
       DateTime local = parseLocal(jp);
       if (local == null) {
         return null;
       }
       return local.toDateMidnight();
   }
   throw ctxt.wrongTokenException(
       jp, JsonToken.START_ARRAY, "expected JSON Array, Number or String");
 }
示例#6
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;
  }
示例#7
0
  /**
   * 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;
  }
  public Response buildResponse(SAMLSSOAuthnReqDTO authReqDTO, String sessionId)
      throws IdentityException {

    if (log.isDebugEnabled()) {
      log.debug(
          "Building SAML Response for the consumer '" + authReqDTO.getAssertionConsumerURL() + "'");
    }
    Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject();
    response.setIssuer(SAMLSSOUtil.getIssuer());
    response.setID(SAMLSSOUtil.createID());
    response.setInResponseTo(authReqDTO.getId());
    response.setDestination(authReqDTO.getAssertionConsumerURL());
    response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null));
    response.setVersion(SAMLVersion.VERSION_20);
    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter =
        new DateTime(
            issueInstant.getMillis() + SAMLSSOUtil.getSAMLResponseValidityPeriod() * 60 * 1000);
    response.setIssueInstant(issueInstant);
    Assertion assertion = buildSAMLAssertion(authReqDTO, notOnOrAfter, sessionId);
    response.getAssertions().add(assertion);
    if (authReqDTO.isDoSignResponse()) {
      SAMLSSOUtil.setSignature(
          response,
          XMLSignature.ALGO_ID_SIGNATURE_RSA,
          new SignKeyDataHolder(authReqDTO.getUsername()));
    }
    return response;
  }
示例#9
0
 public static void blockUntil(String tag, DateTime startAt, long sleepTime) {
   PeriodFormatter pf =
       new PeriodFormatterBuilder()
           .printZeroAlways()
           .appendHours()
           .appendLiteral("小时")
           .appendMinutes()
           .appendLiteral("分")
           .appendSeconds()
           .appendLiteral("秒")
           .toFormatter();
   while (true) {
     DateTime now = DateTime.now();
     Period p = new Period(now, startAt);
     if (now.isAfter(startAt)) {
       System.out.println("时间到了, 启动!");
       break;
     } else {
       System.out.println("[" + tag + "]" + " 距离开始还有 " + p.toString(pf));
     }
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
   System.out.println("执行...");
 }
示例#10
0
  @Test
  public void shouldDeleteEarlierFormIfNewerMotherFormWithSameInstanceIdHasSameDate() {
    NewForm persistedForm = new NewForm();
    persistedForm.setInstanceId("e34707f8-80c8-4198-bf99-c11c90ba5c98");
    final Date oldFormModifiedDate = DateTime.parse("2012-07-10T12:02:59.923+05:30").toDate();
    persistedForm.setCaste("OldCaste");
    persistedForm.setDateModified(oldFormModifiedDate);
    persistedForm.setServerDateModified(oldFormModifiedDate);
    template.save(persistedForm);

    final String newFormModifiedOn = "2012-07-10T12:02:59.923+05:30";
    final Date newFormModifiedDate = DateTime.parse(newFormModifiedOn).toDate();
    final String newCaste = "NewCaste";

    Map<String, String> motherFormValues =
        new HashMap<String, String>() {
          {
            put("caseId", "94d5374f-290e-409f-bc57-86c2e4bcc43f");
            put("dateModified", newFormModifiedOn);
            put("serverDateModified", newFormModifiedOn);
            put("userId", "89fda0284e008d2e0c980fb13fa0e5bb");
            put("xmlns", "http://bihar.commcarehq.org/pregnancy/new");
            put("instanceId", "e34707f8-80c8-4198-bf99-c11c90ba5c98");
            put("caste", newCaste);
          }
        };

    careService.processAndSaveForms(motherFormValues, new ArrayList<Map<String, String>>());

    List<NewForm> newFormsFromDb = template.loadAll(NewForm.class);
    assertEquals(1, newFormsFromDb.size());
    assertEquals(newFormModifiedDate, newFormsFromDb.get(0).getDateModified());
    assertEquals(newCaste, newFormsFromDb.get(0).getCaste());
  }
  /**
   * Parses a date-time from the given text, returning a new DateTime.
   *
   * <p>The parse will use the zone and chronology specified on this formatter.
   *
   * <p>If the text contains a time zone string then that will be taken into account in adjusting
   * the time of day as follows. If the {@link #withOffsetParsed()} has been called, then the
   * resulting DateTime will have a fixed offset based on the parsed time zone. Otherwise the
   * resulting DateTime will have the zone of this formatter, but the parsed zone may have caused
   * the time to be adjusted.
   *
   * @param text the text to parse, not null
   * @return the parsed date-time, never null
   * @throws UnsupportedOperationException if parsing is not supported
   * @throws IllegalArgumentException if the text to parse is invalid
   */
  public DateTime parseDateTime(String text) {
    InternalParser parser = requireParser();

    Chronology chrono = selectChronology(null);
    DateTimeParserBucket bucket =
        new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear);
    int newPos = parser.parseInto(bucket, text, 0);
    if (newPos >= 0) {
      if (newPos >= text.length()) {
        long millis = bucket.computeMillis(true, text);
        if (iOffsetParsed && bucket.getOffsetInteger() != null) {
          int parsedOffset = bucket.getOffsetInteger();
          DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
          chrono = chrono.withZone(parsedZone);
        } else if (bucket.getZone() != null) {
          chrono = chrono.withZone(bucket.getZone());
        }
        DateTime dt = new DateTime(millis, chrono);
        if (iZone != null) {
          dt = dt.withZone(iZone);
        }
        return dt;
      }
    } else {
      newPos = ~newPos;
    }
    throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
  }
  private void generateTimeComparisons(List<String> timeZoneIds) {
    mDisplayLists.clear();

    // Cache timezone objects
    DateTimeZone[] timeZones = new DateTimeZone[timeZoneIds.size()];
    for (int i = 0; i < timeZoneIds.size(); i++) {
      timeZones[i] = DateTimeZone.forID(timeZoneIds.get(i));
    }

    // Round current time down to the hour
    DateTime dateTime =
        new DateTime().withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);

    // format to local date/time (shorten for more comparisons)
    mDateTimeFormatter =
        timeZones.length < 3 ? DateTimeFormat.shortDateTime() : DateTimeFormat.shortTime();

    // Iterate over the next n hours
    for (int i = 0; i < DISPLAY_HOURS; i++) {
      List<String> displayList = new ArrayList<String>();
      for (DateTimeZone dateTimeZone : timeZones) {
        displayList.add(dateTime.withZone(dateTimeZone).toString(mDateTimeFormatter));
      }
      mDisplayLists.add(displayList);
      dateTime = dateTime.plusHours(1);
    }
  }
    /**
     * returns based on DateTime if is in business hours
     *
     * @param dateTimeString
     * @param dateTimeFormatter
     * @return
     */
    private static BusinessHours isBusinessHours(
        String dateTimeString, DateTimeFormatter dateTimeFormatter) {
      DateTime dateTime = DateTime.parse(dateTimeString, dateTimeFormatter);

      // Weekends
      int day = dateTime.getDayOfWeek();
      if (day > DateTimeConstants.FRIDAY) {
        return BusinessHours.NOPE;
      }

      int minute = dateTime.getMinuteOfDay();

      // GOOD = 9-17
      if (minute >= TimeUnit.HOURS.toMinutes(9) && minute <= TimeUnit.HOURS.toMinutes(17)) {
        return BusinessHours.GOOD;
      }

      // OK = 0800-0859, 1701-1800
      if (minute >= TimeUnit.HOURS.toMinutes(8) && minute < TimeUnit.HOURS.toMinutes(9)
          || (minute > TimeUnit.HOURS.toMinutes(17) && minute <= TimeUnit.HOURS.toMinutes(18))) {
        return BusinessHours.OK;
      }

      // MEH = 0700-0759, 1801-1900
      if (minute >= TimeUnit.HOURS.toMinutes(7) && minute < TimeUnit.HOURS.toMinutes(8)
          || (minute > TimeUnit.HOURS.toMinutes(18) && minute <= TimeUnit.HOURS.toMinutes(19))) {
        return BusinessHours.MEH;
      }

      return BusinessHours.NOPE;
    }
  /**
   * Handles the Time.now macro
   *
   * @param tokens list of tokens
   * @param iter iterator used to iterate over the list of tokens
   * @return string containing the interpolated time token
   */
  private static String handleTime(List<String> tokens, Iterator<String> iter) {
    DateTime dt = new DateTime();

    // Add some amount
    if (iter.hasNext()) {
      String operationToken = iter.next();
      if (operationToken.equals("+") || operationToken.equals("-")) {
        if (iter.hasNext()) {
          String quantityToken = iter.next(); // Get the magnitude to
          // add or subtract

          ReadablePeriod period = getTimePeriod(quantityToken);

          if (operationToken.equals("-")) {
            dt = dt.minus(period);
          } else {
            dt = dt.plus(period);
          }
        } else {
          logger.warn("Token '{}' not followed by a quantity", operationToken);
        }
      } else {
        logger.warn("Invalid token '{}', must be operator '+' or '-'", operationToken);
      }
    }

    return DATE_UTIL.formatDateTime(dt);
  }
  @Test
  public void correctToStringResult() {
    final TLE tle = new TLE(LEO_TLE);

    Assert.assertTrue(!tle.isDeepspace());

    try {
      final PassPredictor passPredictor = new PassPredictor(tle, GROUND_STATION);
      final DateTime cal = new DateTime(DATE_2009_01_05T04_30_00Z);
      final SatPassTime passTime = passPredictor.nextSatPass(cal.toDate(), true);

      Assert.assertEquals(
          "Date: January 5, 2009\n"
              + "Start Time: 4:28 AM\n"
              + "Duration:  4.1 min.\n"
              + "AOS Azimuth: 52 deg.\n"
              + "Max Elevation:  0.9 deg.\n"
              + "LOS Azimuth: 84 deg.",
          passTime.toString());
    } catch (final InvalidTleException e) {
      Assert.fail(INVALID_TLE_EXCEPTION_WAS_THROWN);
    } catch (final SatNotFoundException snfe) {
      Assert.fail(SAT_NOT_FOUND_EXCEPTION_WAS_THROWN);
    }
  }
  public void testAutoCreateIndexWithDateMathExpression() throws Exception {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));

    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    client().prepareIndex(dateMathExp1, "type", "1").setSource("{}").get();
    client().prepareIndex(dateMathExp2, "type", "2").setSource("{}").get();
    client().prepareIndex(dateMathExp3, "type", "3").setSource("{}").get();
    refresh();

    SearchResponse searchResponse =
        client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertHitCount(searchResponse, 3);
    assertSearchHits(searchResponse, "1", "2", "3");

    IndicesStatsResponse indicesStatsResponse =
        client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
  }
  /*
   * 20 days old ->  O O    <- 10 days old
   *                 |/
   *    ancestor ->  O   O  <- 5 days old
   *                  \ /
   *        root ->    O
   *
   * Creates a small repository of 5 commits with different branches and ages.
   */
  @Before
  public void setUp() throws Exception {
    Set<String> prevBranches = stringifyBranches(testGitClient.getBranches());

    testGitClient.commit("Root Commit");
    rootCommit = getLastCommitSha1(prevBranches);

    testGitClient.commit("Ancestor Commit");
    ancestorCommit = getLastCommitSha1(prevBranches);

    testGitClient.branch("20-days-old-branch");
    testGitClient.checkoutBranch("20-days-old-branch", ancestorCommit);
    this.commit(
        "20 days ago commit message",
        new PersonIdent(johnDoe, twentyDaysAgo.toDate()),
        new PersonIdent(johnDoe, twentyDaysAgo.toDate()));
    twentyDaysAgoCommit = getLastCommitSha1(prevBranches);

    testGitClient.checkout().ref(ancestorCommit).execute();
    testGitClient.checkoutBranch("10-days-old-branch", ancestorCommit);
    this.commit(
        "10 days ago commit message",
        new PersonIdent(johnDoe, tenDaysAgo.toDate()),
        new PersonIdent(johnDoe, tenDaysAgo.toDate()));
    tenDaysAgoCommit = getLastCommitSha1(prevBranches);

    testGitClient.checkout().ref(rootCommit).execute();
    testGitClient.checkoutBranch("5-days-old-branch", rootCommit);
    this.commit(
        "5 days ago commit message",
        new PersonIdent(johnDoe, fiveDaysAgo.toDate()),
        new PersonIdent(johnDoe, fiveDaysAgo.toDate()));
    fiveDaysAgoCommit = getLastCommitSha1(prevBranches);
  }
  protected LogoutRequest buildLogoutRequest(String user, String sessionIdx)
      throws SSOAgentException {

    LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject();

    logoutReq.setID(SSOAgentUtils.createID());
    logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());
    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
    nameId.setValue(user);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIdx);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason("Single Logout");

    return logoutReq;
  }
示例#19
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;
  }
 @Test
 public void testTimeToNextExecution() throws Exception {
   DateTime now = truncateToSeconds(DateTime.now());
   DateTime expected = truncateToSeconds(now.plusSeconds(1));
   ExecutionTime executionTime = ExecutionTime.forCron(quartzCronParser.parse(EVERY_SECOND));
   assertEquals(new Interval(now, expected).toDuration(), executionTime.timeToNextExecution(now));
 }
  private void execute() {
    search();
    // from home - find more candidates
    String findDue = (String) data.get("findDue");
    if (FieldUtil.isNotEmpty(findDue)) {

      LOGGER.debug(findDue);
      // 設條件
      DateField dfFrom = (DateField) gridFilter.getField("dueOn" + "_From");
      DateField dfTo = (DateField) gridFilter.getField("dueOn" + "_To");

      if (findDue.equals(CardDonut.MODE_DUE.DUE_TODAY.getValue())) {
        dfFrom.setValue(DateUtil.getOnlyDate(new Date(), timeZone));
        dfTo.setValue(DateUtil.getOnlyDate(new Date(), timeZone));
      } else if (findDue.equals(CardDonut.MODE_DUE.OVERDUE.getValue())) {
        DateTime dt = new DateTime();
        dfTo.setValue(DateUtil.getOnlyDate(dt.minusDays(1).toDate(), timeZone));
      } else if (findDue.equals(CardDonut.MODE_DUE.TOTAL.getValue())) {

      }
      // 清除
      data.put("findDue", null);
      UI.getCurrent().setData(data);

      gridFilter.search();
    }
  }
 @Test
 public void testLastExecution() throws Exception {
   DateTime now = truncateToSeconds(DateTime.now());
   DateTime expected = truncateToSeconds(now.minusSeconds(1));
   ExecutionTime executionTime = ExecutionTime.forCron(quartzCronParser.parse(EVERY_SECOND));
   assertEquals(expected, executionTime.lastExecution(now));
 }
 @Test
 public void
     givenKnownOrganizationIdAndTimePeriodWhenQueringStateModificationOfVirtualMachinesThenModificationMustBeAccessibleFromRepositoryInterfaceDuringDefinedTimePeriod() {
   long organizationId = System.currentTimeMillis();
   UsageHour expected = new UsageHour();
   expected.setClusterId(123456);
   expected.setMachineId(654321);
   expected.setOrganizationId(organizationId);
   expected.setPlatformId(2);
   expected.setVirtualMachineState(VirtualMachineState.STARTED);
   usageHourRepository.store(expected);
   DateTime startTime = new DateTime(1979, 4, 3, 12, 0, 0, 0);
   DateTime endTime = new DateTime(2079, 4, 3, 12, 0, 0, 0);
   Collection<UsageHour> usageHours =
       usageHourRepository.loadUsageHoursByOrganizationIdAndUsagePeriod(
           organizationId, startTime.toDate(), endTime.toDate());
   assertEquals(1, usageHours.size());
   UsageHour actual = null;
   for (UsageHour usage : usageHours) {
     actual = usage;
   }
   assertEquals(expected.getClusterId(), actual.getClusterId());
   assertEquals(expected.getMachineId(), actual.getMachineId());
   assertEquals(expected.getOrganizationId(), actual.getOrganizationId());
   assertEquals(expected.getPlatformId(), actual.getPlatformId());
   assertEquals(
       expected.getVirtualMachineState().getValue(), actual.getVirtualMachineState().getValue());
   assertNotNull(actual.getTimeStamp());
   assertNotSame(expected.getId(), actual.getId());
 }
示例#24
0
  public static void testLocale() {

    System.out.println("演示Locale");

    DateTime dateTime = new DateTime().withZone(DateTimeZone.UTC);

    // 打印中文与英文下不同长度的日期格式串
    System.out.println("S:  " + DateUtils.formatDateTime(dateTime, "SS", "zh"));
    System.out.println("M:  " + DateUtils.formatDateTime(dateTime, "MM", "zh"));
    System.out.println("L:  " + DateUtils.formatDateTime(dateTime, "LL", "zh"));
    System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "zh"));
    System.out.println("");

    System.out.println("S:  " + DateUtils.formatDateTime(dateTime, "SS", "en"));
    System.out.println("M:  " + DateUtils.formatDateTime(dateTime, "MM", "en"));
    System.out.println("L:  " + DateUtils.formatDateTime(dateTime, "LL", "en"));
    System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "en"));
    System.out.println("");
    System.out.println("");

    // 直接打印TimeStamp, 日期是M,时间是L
    DateTimeFormatter formatter =
        DateTimeFormat.forStyle("ML").withLocale(new Locale("zh")).withZone(DateTimeZone.UTC);

    System.out.println("ML Mix: " + formatter.print(dateTime.getMillis()));

    // 只打印日期不打印时间
    System.out.println("Date only :" + DateUtils.formatDateTime(dateTime, "M-", "zh"));
  }
  @Override
  protected Object onGetDefaultValue(TypedArray a, int index) {
    String defaultDateSpecifiedInPref = a.getString(index);

    if (defaultDateSpecifiedInPref != null) // if the default date is
    // specified in the preferences
    {
      if (defaultDateSpecifiedInPref.equals(DATE_TIME_NOW)) // if todays
        // date should
        // be as
        // default
        this.mDefaultDate = DateTime.now();
      else // given date is specificed in the preferences
      {
        try // try to parse it
        {
          this.mDefaultDate =
              DateTime.parse(defaultDateSpecifiedInPref, DateUtils.SHORT_DATE_FORMAT);
        } catch (Exception e) // if the parsing fails, just initiate the
        // defafult date variable
        {
          this.mDefaultDate = new DateTime();
        }
      }
    } else // no default date is specified in the preferences
    {
      this.mDefaultDate = new DateTime();
    }

    return this.mDefaultDate.getMillis(); // return the date in millisecunds
  }
示例#26
0
  public void testGetSigningBlessingNames() throws VException {
    VContext context = V.init();
    VPrincipal p = VSecurity.newPrincipal();
    ECPublicKey pk = p.publicKey();
    List<Caveat> passingCaveats =
        ImmutableList.of(
            VSecurity.newExpiryCaveat(DateTime.now().plusDays(1)),
            VSecurity.newExpiryCaveat(DateTime.now().plusYears(1)));
    List<Caveat> failingCaveats =
        ImmutableList.of(
            VSecurity.newMethodCaveat("MethodName"), VSecurity.newExpiryCaveat(DateTime.now()));

    Blessings b1 = p.blessSelf("alice");
    Blessings b2 = p.blessSelf("alice");
    Blessings passing =
        p.bless(
            pk,
            b1,
            "passing",
            passingCaveats.get(0),
            passingCaveats.subList(1, passingCaveats.size()).toArray(new Caveat[0]));
    Blessings failing =
        p.bless(
            pk,
            b2,
            "failing",
            failingCaveats.get(0),
            failingCaveats.subList(1, failingCaveats.size()).toArray(new Caveat[0]));
    Blessings union = VSecurity.unionOfBlessings(new Blessings[] {passing, failing});
    VSecurity.addToRoots(p, passing);

    String[] signingBlessingNames = VSecurity.getSigningBlessingNames(context, p, union);
    assertThat(Arrays.asList(signingBlessingNames)).containsExactly("alice:passing");
  }
示例#27
0
 @Override
 public int hashCode() {
   int result = id != null ? id.hashCode() : 0;
   result = 31 * result + (createdDate != null ? createdDate.hashCode() : 0);
   result = 31 * result + (updatedDate != null ? updatedDate.hashCode() : 0);
   return result;
 }
  /**
   * Test method for {@link uk.me.g4dpz.satellite.PassPredictor#nextSatPass(java.util.Date,
   * boolean)}.
   */
  @Test
  public final void testNextSatPassWithWindBack() {

    final TLE tle = new TLE(LEO_TLE);

    Assert.assertTrue(!tle.isDeepspace());

    try {
      final PassPredictor passPredictor = new PassPredictor(tle, GROUND_STATION);
      final DateTime cal = new DateTime(DATE_2009_01_05T04_30_00Z);
      final SatPassTime passTime = passPredictor.nextSatPass(cal.toDate(), true);
      Assert.assertEquals(DATE_2009_01_05T04_28_10_0000, TZ_FORMAT.format(passTime.getStartTime()));
      Assert.assertEquals(DATE_2009_01_05T04_32_15_0000, TZ_FORMAT.format(passTime.getEndTime()));
      Assert.assertEquals(NONE, passTime.getPolePassed());
      Assert.assertEquals(52, passTime.getAosAzimuth());
      Assert.assertEquals(84, passTime.getLosAzimuth());
      Assert.assertEquals(0.9, passTime.getMaxEl(), 0.05);
      Assert.assertEquals(
          Long.valueOf(436802379L),
          passPredictor.getDownlinkFreq(436800000L, passTime.getStartTime()));
      Assert.assertEquals(
          Long.valueOf(145800719L), passPredictor.getUplinkFreq(145800000L, passTime.getEndTime()));
    } catch (final InvalidTleException e) {
      Assert.fail(INVALID_TLE_EXCEPTION_WAS_THROWN);
    } catch (final SatNotFoundException snfe) {
      Assert.fail(SAT_NOT_FOUND_EXCEPTION_WAS_THROWN);
    }
  }
  @Test
  public void testToStringForTimeZone_fromApiDate() {
    Assert.assertEquals(
        stringDateTime1, DateTimes.toStringForTimeZone(apiDateTime1, TIME_ZONE_ID1));
    Assert.assertEquals(
        stringDateTime2, DateTimes.toStringForTimeZone(apiDateTime2, TIME_ZONE_ID2));
    Assert.assertEquals(
        stringDateTime3, DateTimes.toStringForTimeZone(apiDateTime3, TIME_ZONE_ID3));

    Assert.assertEquals(
        stringDateTime1,
        DateTimes.toStringForTimeZone(
            DateTimes.toDateTime(jodaDateTime1.withZone(DateTimeZone.forID(TIME_ZONE_ID2))),
            TIME_ZONE_ID1));
    Assert.assertEquals(
        stringDateTime2,
        DateTimes.toStringForTimeZone(
            DateTimes.toDateTime(jodaDateTime2.withZone(DateTimeZone.forID(TIME_ZONE_ID1))),
            TIME_ZONE_ID2));
    Assert.assertEquals(
        stringDateTime3,
        DateTimes.toStringForTimeZone(
            DateTimes.toDateTime(jodaDateTime3.withZone(DateTimeZone.forID(TIME_ZONE_ID1))),
            TIME_ZONE_ID3));
  }
  public static void main(String[] args) {
    DateTime a = new DateTime();
    DateTime b = a.minusMonths(8);

    System.out.println(Months.monthsBetween(a, b).getMonths());
    System.out.println(Months.monthsBetween(b, a).getMonths());
  }