Esempio n. 1
0
  @Test
  public void dates_should_be_serialized_in_ISO_8601_format() {
    setupNegativeContains("some_id");
    when(httpClient.put(anyString(), anyString()))
        .thenReturn(
            HttpResponseStub.valueOf(201, "{\"ok\":true,\"id\":\"some_id\",\"rev\":\"123D123\"}"));

    DateTime dt = new DateTime(2010, 4, 25, 20, 11, 24, 555, DateTimeZone.forID("+00:00"));
    Date d = dt.toDate();
    System.out.println(d);
    DateDoc dd = new DateDoc();
    dd.setId("some_id");
    dd.setDateTime(dt);
    dd.setDate(dt.toDate());

    dbCon.create(dd);

    ArgumentCaptor<String> ac = ArgumentCaptor.forClass(String.class);
    verify(httpClient).put(eq("/test_db/some_id"), ac.capture());
    String json = ac.getValue();
    assertEqualJson("dates.json", json);

    when(httpClient.get("/test_db/some_id")).thenReturn(HttpResponseStub.valueOf(201, json));

    DateDoc deserialized = dbCon.get(DateDoc.class, dd.getId());
    assertEquals(dt, deserialized.getDateTime());
    assertEquals(d, deserialized.getDate());
  }
 @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());
 }
  @Test
  public void shouldGetAllPeriodsForPeriodDateRange() throws Exception {
    DateTime currentDate = DateTime.parse("2013-01-01");
    ProcessingPeriod period1 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(1).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month1")));
    ProcessingPeriod period2 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusMonths(1).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(2).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month2")));
    ProcessingPeriod period3 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusMonths(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(3).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month3")));
    ProcessingPeriod period4 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.plusDays(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(1).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month4")));
    ProcessingPeriod period5 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, currentDate.minusDays(2).toDate()),
                with(ProcessingPeriodBuilder.endDate, currentDate.plusMonths(3).toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month5")));

    mapper.insert(period1);
    mapper.insert(period2);
    mapper.insert(period3);
    mapper.insert(period4);
    mapper.insert(period5);
    DateTime searchStartDate = currentDate;
    DateTime searchEndDate = searchStartDate.plusDays(45);
    List<ProcessingPeriod> searchResults =
        mapper.getAllPeriodsForDateRange(
            schedule.getId(), searchStartDate.toDate(), searchEndDate.toDate());
    for (ProcessingPeriod period : searchResults) {
      period.setModifiedDate(null);
    }
    assertThat(searchResults, is(hasItems(period1, period2, period4, period5)));
    assertThat(searchResults, is(not(hasItems(period3))));
  }
Esempio n. 4
0
  @Test
  public final void shouldCreateCorrectOrderDates3() {
    // given
    Entity order = mockOrder(START_DATE_1.toDate(), null, null, END_DATE_1.toDate(), null, null);

    // when
    Optional<OrderDates> maybeOrderDates = OrderDates.of(order);

    // then
    Assert.assertTrue(maybeOrderDates.isPresent());
    OrderDates orderDates = maybeOrderDates.get();

    Assert.assertEquals(START_DATE_1, orderDates.getStart().planned());
    Assert.assertEquals(Optional.<LocalDate>absent(), orderDates.getStart().corrected());
    Assert.assertEquals(Optional.<LocalDate>absent(), orderDates.getStart().effective());

    Assert.assertEquals(START_DATE_1, orderDates.getStart().correctedWithFallback());
    Assert.assertEquals(START_DATE_1, orderDates.getStart().effectiveWithFallback());

    Assert.assertEquals(END_DATE_1, orderDates.getEnd().planned());
    Assert.assertEquals(Optional.<LocalDate>absent(), orderDates.getEnd().corrected());
    Assert.assertEquals(Optional.<LocalDate>absent(), orderDates.getEnd().effective());

    Assert.assertEquals(END_DATE_1, orderDates.getEnd().correctedWithFallback());
    Assert.assertEquals(END_DATE_1, orderDates.getEnd().effectiveWithFallback());
  }
  @Test
  public void shouldReturnAllPeriodsForASchedule() throws Exception {
    DateTime date1 = new DateTime();
    DateTime date2 = date1.plusMonths(3);

    ProcessingPeriod period1 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, date1.toDate()),
                with(scheduleId, schedule.getId())));
    ProcessingPeriod period2 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, date2.toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month2")));

    mapper.insert(period1);
    mapper.insert(period2);

    List<ProcessingPeriod> fetchedPeriods = mapper.getAll(schedule.getId());
    assertThat(fetchedPeriods.size(), is(2));
    assertThat(fetchedPeriods.get(0).getId(), is(period2.getId()));
  }
  /*
   * 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);
  }
  @Test
  public void shouldReturnLastAddedPeriodForASchedule() throws Exception {
    DateTime date1 = new DateTime();
    DateTime date2 = date1.plusMonths(3);

    ProcessingPeriod period1 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, date1.toDate()),
                with(scheduleId, schedule.getId())));
    ProcessingPeriod period2 =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.startDate, date2.toDate()),
                with(scheduleId, schedule.getId()),
                with(name, "Month2")));

    mapper.insert(period1);
    mapper.insert(period2);

    ProcessingPeriod fetchedPeriod = mapper.getLastAddedProcessingPeriod(schedule.getId());
    assertThat(fetchedPeriod.getId(), is(period2.getId()));
  }
 @ActionMapping("add")
 public void addPerson(
     @Valid @ModelAttribute Person person,
     BindingResult result,
     ActionRequest actionRequest,
     ActionResponse actionResponse,
     SessionStatus sessionStatus,
     Model model) {
   if (!result.hasErrors()) {
     logger.info("ACTION: action saving person = " + person);
     try {
       DateTime dt1 = DateTime.now();
       DateTime dt2 = dt1.plusYears(10);
       IdentityCard identityCard =
           new IdentityCard(person, "BL", "112233", dt1.toDate(), dt2.toDate());
       identityCard.setAddress("-");
       person.setIdentityCard(identityCard);
       personManager.save(person);
       model.addAttribute(
           "message",
           messageSource.getMessage("label.Person.saved", null, actionRequest.getLocale()));
       sessionStatus.setComplete();
     } catch (Exception e) {
       logger.error("Unexpected error when saving person.", e);
       model.addAttribute("error", "Internal Error. Contact Administrator.");
     }
   } else {
     logger.info("Validation failed");
     model.addAttribute("errors", result);
   }
 }
  @Override
  public AuthorizationRequest createAuthorizationRequest(Map<String, String> parameters) {

    String clientId = parameters.get("client_id");
    if (clientId == null) {
      throw new InvalidClientException("A client id must be provided");
    }
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    String requestNonce = parameters.get("nonce");

    // Only process if the user is authenticated. If the user is not authenticated yet, this
    // code will be called a second time once the user is redirected from the login page back
    // to the auth endpoint.
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (requestNonce != null && principal != null && principal instanceof User) {

      // Check request nonce for reuse
      Collection<Nonce> clientNonces = nonceService.getByClientId(client.getClientId());
      for (Nonce nonce : clientNonces) {
        String nonceVal = nonce.getValue();
        if (nonceVal.equals(requestNonce)) {
          throw new NonceReuseException(client.getClientId(), nonce);
        }
      }

      // Store nonce
      Nonce nonce = new Nonce();
      nonce.setClientId(client.getClientId());
      nonce.setValue(requestNonce);
      DateTime now = new DateTime(new Date());
      nonce.setUseDate(now.toDate());
      DateTime expDate = now.plus(nonceStorageDuration);
      Date expirationJdkDate = expDate.toDate();
      nonce.setExpireDate(expirationJdkDate);

      nonceService.save(nonce);
    }

    Set<String> scopes = OAuth2Utils.parseParameterList(parameters.get("scope"));
    if ((scopes == null || scopes.isEmpty())) {
      // TODO: do we want to allow default scoping at all?
      // If no scopes are specified in the incoming data, it is possible to default to the client's
      // registered scopes, but minus the "openid" scope. OpenID Connect requests MUST have the
      // "openid" scope.
      Set<String> clientScopes = client.getScope();
      if (clientScopes.contains("openid")) {
        clientScopes.remove("openid");
      }
      scopes = clientScopes;
    }
    DefaultAuthorizationRequest request =
        new DefaultAuthorizationRequest(
            parameters, Collections.<String, String>emptyMap(), clientId, scopes);
    request.addClientDetails(client);
    return request;
  }
  /** Set all date and time button labels (with selected dates). */
  private void setButtonLabel() {
    java.text.DateFormat formatDate = DateFormat.getDateFormat(this);
    btDatePickerStart.setText(formatDate.format(dateTimeStart.toDate()));
    btDatePickerEnd.setText(formatDate.format(dateTimeEnd.toDate()));

    java.text.DateFormat formatTime = DateFormat.getTimeFormat(this);
    btTimePickerStart.setText(formatTime.format(dateTimeStart.toDate()));
    btTimePickerEnd.setText(formatTime.format(dateTimeEnd.toDate()));
  }
 @Test
 public void shouldGetEmptyHolderWhenExceptionIsThrown() throws ScmException {
   DateRange dateRange = new DateRange(datefrom, dateTo);
   when(scmFacade.getChangeLog(projectBaseDir, datefrom.toDate(), dateTo.toDate()))
       .thenThrow(ScmException.class);
   GenericScmAdapter genericScmAdapter =
       new GenericScmAdapter(scmFacade, config, fileExclusions, moduleFileSystem);
   ChangeLogHandler changeLogHandler = genericScmAdapter.getChangeLog(dateRange);
   assertThat(changeLogHandler.getChangeLogs()).isEmpty();
 }
Esempio n. 12
0
  public List<CustomerScheduleEntity> getCustomerSchedulesForAccountThatAreWithinDates(
      Integer accountId, DateTime fromDate, DateTime thruDate) throws PersistenceException {

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("ACCOUNT_ID", accountId);
    parameters.put("FROM_DATE", DateUtils.getLocalDateFromDate(fromDate.toDate()).toString());
    parameters.put("THRU_DATE", DateUtils.getLocalDateFromDate(thruDate.toDate()).toString());

    return executeNamedQuery("getCustomerSchedulesForAccountThatAreWithinDates", parameters);
  }
 @Before
 public void init() throws ScmException {
   when(moduleFileSystem.baseDir()).thenReturn(projectBaseDir);
   when(changeLog.getChangeLog()).thenReturn(changeLogSet);
   when(changeLogSet.getChangeSets()).thenReturn(changeSets);
   when(scmFacade.getChangeLog(projectBaseDir, datefrom.toDate(), dateTo.toDate()))
       .thenReturn(changeLog);
   when(fileExclusions.sourceExclusions()).thenReturn(new String[0]);
   when(fileExclusions.sourceInclusions()).thenReturn(new String[0]);
 }
Esempio n. 14
0
  @Test(groups = "slow")
  public void testBasic() throws InterruptedException {
    final String ownerId = UUID.randomUUID().toString();

    final String notificationKey = UUID.randomUUID().toString();
    final DateTime effDt = new DateTime();
    final Notification notif =
        new DefaultNotification(
            "testBasic",
            hostname,
            notificationKey.getClass().getName(),
            notificationKey,
            accountId,
            effDt);
    dao.insertNotification(notif);

    Thread.sleep(1000);
    final DateTime now = new DateTime();
    final List<Notification> notifications =
        dao.getReadyNotifications(now.toDate(), hostname, 3, "testBasic");
    assertNotNull(notifications);
    assertEquals(notifications.size(), 1);

    Notification notification = notifications.get(0);
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    assertEquals(notification.getOwner(), null);
    assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.AVAILABLE);
    assertEquals(notification.getNextAvailableDate(), null);

    final DateTime nextAvailable = now.plusMinutes(5);
    final int res =
        dao.claimNotification(
            ownerId, nextAvailable.toDate(), notification.getId().toString(), now.toDate());
    assertEquals(res, 1);
    dao.insertClaimedHistory(ownerId, now.toDate(), notification.getId().toString());

    notification = fetchNotification(notification.getId().toString());
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    assertEquals(notification.getOwner(), ownerId);
    assertEquals(
        notification.getProcessingState(), PersistentQueueEntryLifecycleState.IN_PROCESSING);
    validateDate(notification.getNextAvailableDate(), nextAvailable);

    dao.clearNotification(notification.getId().toString(), ownerId);

    notification = fetchNotification(notification.getId().toString());
    assertEquals(notification.getNotificationKey(), notificationKey);
    validateDate(notification.getEffectiveDate(), effDt);
    // assertEquals(notification.getOwner(), null);
    assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.PROCESSED);
    validateDate(notification.getNextAvailableDate(), nextAvailable);
  }
  private X509Certificate generateCertificate(
      PublicKey subjectPublicKey,
      String subjectDn,
      DateTime notBefore,
      DateTime notAfter,
      X509Certificate issuerCertificate,
      PrivateKey issuerPrivateKey)
      throws Exception {

    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());

    X509Principal issuerDN;
    if (null != issuerCertificate) {
      issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
      issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(
        X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey));

    PublicKey issuerPublicKey;
    if (null != issuerCertificate) {
      issuerPublicKey = issuerCertificate.getPublicKey();
    } else {
      issuerPublicKey = subjectPublicKey;
    }
    certificateGenerator.addExtension(
        X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate =
        (X509Certificate)
            certificateFactory.generateCertificate(
                new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
  }
Esempio n. 16
0
 public static Set<ArchetypeReference> filterEHRData(
     String ehrId,
     DateTime ehrDate,
     Collection<ArchetypeReference> queryARs,
     Collection<ElementInstance> elementInstances) {
   Set<ArchetypeReference> ehrIdARs = new HashSet<ArchetypeReference>();
   if (elementInstances == null) {
     Logger.getLogger(EHRDataFilterUtil.class).warn("No ehrData found for ehrId '" + ehrId + "'");
   } else {
     // We iterate through archetype references instead of
     Set<ArchetypeReference> auxEHRIdsARs = new HashSet<ArchetypeReference>();
     for (ElementInstance elementInstance : elementInstances) {
       auxEHRIdsARs.add(elementInstance.getArchetypeReference());
     }
     for (ArchetypeReference archetypeReference : auxEHRIdsARs) {
       // If using time series comparison filter elements outside the range
       boolean useAR = true;
       if (ehrDate != null) {
         DateTime dateTime = DateTimeARFinder.getDateTime(archetypeReference);
         // DateFormat df2 = DateFormat.getDateTimeInstance();
         // Logger.getLogger(DashboardFetchPageExecutionThread.class).debug("Comparing '"+ehrId+"'
         // with ehr date '"+df2.format(ehrDate.toDate())+"' to date
         // '"+(dateTime==null?"null":df2.format(dateTime.toDate()))+"' eiId =
         // '"+elementInstance.getId()+"'");
         if (dateTime == null || dateTime.isAfter(ehrDate)) {
           useAR = false;
           DateFormat df = DateFormat.getDateTimeInstance();
           if (dateTime == null) {
             Logger.getLogger(EHRDataFilterUtil.class)
                 .warn(
                     "Date time for ehrId "
                         + ehrId
                         + " with AR "
                         + archetypeReference.getIdArchetype()
                         + " is null!");
           } else {
             Logger.getLogger(EHRDataFilterUtil.class)
                 .debug(df.format(dateTime.toDate()) + " after " + df.format(ehrDate.toDate()));
           }
         }
       }
       if (useAR) {
         ehrIdARs.add(archetypeReference);
       }
     }
     // Fill missing data
     Calendar date = Calendar.getInstance();
     if (ehrDate != null) {
       date = ehrDate.toGregorianCalendar();
     }
     PredicateFilterUtil.filterByPredicates(queryARs, ehrIdARs, date);
   }
   return ehrIdARs;
 }
 private void adjustIntervalStartAndEndDate(
     DateTime thresholdDateView, IntervalBase interval, IntervalBase clonedInterval) {
   if (interval.getStart().before(thresholdDateView.toDate())) {
     // Set start of the interval to threshold if the start is
     // before the threshold.
     clonedInterval.setStartTime(thresholdDateView.toDate());
   }
   if (!clonedInterval.isClosed()) {
     clonedInterval.setEndTime(mostRecentDate);
   }
 }
Esempio n. 18
0
  @Transactional
  @Rollback(true)
  @Test
  public void testGetAuthorizedDevicesExceptSome() {
    String userId = "userId";
    String udid = "udid";
    String deviceId = "deviceId";

    String udid2 = "udid2";
    String deviceId2 = "deviceId2";

    DateTime expiry = new DateTime();
    expiry = expiry.plusDays(PoConstants.AUTHORIZED_DEVICE__TOKEN_LIFE_EXPECTANCY_DAYS);

    // first device for user
    AuthorizedDevice ad = new AuthorizedDevice();
    ad.setUserId(userId);
    ad.setUdid(udid);
    ad.setDeviceId(deviceId);
    ad.setExpires(expiry.toDate());

    // second device for user
    AuthorizedDevice ad2 = new AuthorizedDevice();
    ad2.setUserId(userId);
    ad2.setUdid(udid2);
    ad2.setDeviceId(deviceId2);
    ad2.setExpires(expiry.toDate());

    // save both to the database
    List<AuthorizedDevice> adList = new ArrayList<AuthorizedDevice>();
    adList.add(ad2);
    adList.add(ad);
    getAuthorizedDeviceDao().save(ad);
    getAuthorizedDeviceDao().save(adList);

    long deviceCount = getAuthorizedDeviceDao().count();
    Assert.assertTrue(deviceCount > 0);
    // the authorized device ids to exclude
    List<String> id = new ArrayList<String>();
    id.add(ad.getId());

    // log.error("adList=" + adList);
    // log.error("id=" + id);

    // get all but the first device for user
    assertNotNull("wtf userId is null", userId);
    assertNotNull("wtf id is null", id);
    assertTrue("id=" + id, !id.isEmpty());
    List<AuthorizedDevice> inDbList = getAuthorizedDeviceDao().findByUserIdAndIdNotIn(userId, id);

    assertTrue("inDbList=" + inDbList, inDbList.size() == 1);
    log.info("Should be same objects: inDbList=" + inDbList + " ad2=" + ad2);
  }
Esempio n. 19
0
  public static void main(String args[]) {

    TimeZone.setDefault(TimeZone.getTimeZone("America/Bogota"));

    DateTime dt = new DateTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //		System.out.println("- " + sdf.format(dt.toDate()));
    //		sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    //		System.out.println("- " + sdf.format(dt.toDate()));

    String sd = "2011-03-18 16:30:39";
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    Date d = null;
    try {
      d = sdf.parse(sd);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    System.out.println("- " + sdf.format(d));
    sdf.setTimeZone(TimeZone.getTimeZone("America/Bogota"));
    System.out.println("- " + sdf.format(d));

    try {
      d = sdf.parse(sd);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    System.out.println("- " + sdf.format(d));

    DateTime nDt = dt.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Shanghai")));
    System.out.println(sdf.format(nDt.toDate()));

    DateTime dt2 = new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Tokyo")));

    sdf.setTimeZone(TimeZone.getTimeZone("America/Bogota"));
    System.out.println(sdf.format(dt2.toDate()));

    //		System.out.println(getFormatedDateString(""));
    //		System.out.println(getFormatedDateString("America/Bogota"));
    //
    //		//printSysProperties();
    //
    //		System.out.println("------------------------------------------");
    ////		System.setProperty("user.timezone", "America/Bogota");
    //		TimeZone.setDefault(TimeZone.getTimeZone("America/Bogota"));
    //
    //		System.out.println(getFormatedDateString(""));
    //		System.out.println(getFormatedDateString("Asia/Shanghai"));

    // printSysProperties();
  }
Esempio n. 20
0
  @Test
  public void testGetPreviousPeriod() {
    testDate = new DateTime(2009, 8, 15, 0, 0);

    Period period = periodType.createPeriod(testDate.toDate());

    period = periodType.getPreviousPeriod(period);

    startDate = new DateTime(2009, 5, 1, 0, 0);
    endDate = new DateTime(2009, 6, 30, 0, 0);

    assertEquals(startDate.toDate(), period.getStartDate());
    assertEquals(endDate.toDate(), period.getEndDate());
  }
  private ProcessingPeriod insertProcessingPeriod(
      String name, DateTime startDate, DateTime endDate) {
    ProcessingPeriod period =
        make(
            a(
                defaultProcessingPeriod,
                with(ProcessingPeriodBuilder.name, name),
                with(scheduleId, schedule.getId()),
                with(ProcessingPeriodBuilder.startDate, startDate.toDate()),
                with(ProcessingPeriodBuilder.endDate, endDate.toDate())));

    mapper.insert(period);
    return period;
  }
Esempio n. 22
0
 public void isLatestTime(Account account, Region region, ResourceType resourceType, DateTime dt) {
   Validate.noNullElements(new Object[] {account, region, resourceType, dt});
   Optional<Ec2Version> oEc2Version =
       awsService.findLatestEc2Version(account.getId(), resourceType, region);
   if (oEc2Version.isPresent()) {
     Ec2Version ec2Version = oEc2Version.get();
     if (ec2Version.getTimeDetected().after(dt.toDate())) {
       throw new IllegalArgumentException(
           String.format(
               "latest ec2version is:%s which is later than datetime:%s",
               ec2Version.getTimeDetected(), dt.toDate()));
     }
   }
 }
Esempio n. 23
0
  @Test
  public void niceTimeDeltaCanBeOutputInAlterativeLangauges() throws Exception {
    final DateTime now = DateTime.now().minusSeconds(1);

    DateTime lessThanOneMinuteAgo = now.minusSeconds(30);
    assertEquals("En este momento", spanishDateFormatter.timeSince(lessThanOneMinuteAgo.toDate()));

    DateTime oneMinuteAgo = now.minusSeconds(70);
    assertEquals("Hace 1 minuto", spanishDateFormatter.timeSince(oneMinuteAgo.toDate()));

    DateTime fiveMinutesBefore = now.minusMinutes(5);
    assertEquals("Hace 5 minutos", spanishDateFormatter.timeSince(fiveMinutesBefore.toDate()));

    DateTime anHourAgo = now.minusHours(1);
    assertEquals("Hace 1 hora", spanishDateFormatter.timeSince(anHourAgo.toDate()));

    DateTime twoHoursAgo = now.minusHours(2);
    assertEquals("Hace 2 horas", spanishDateFormatter.timeSince(twoHoursAgo.toDate()));

    DateTime oneDayAgo = now.minusDays(1);
    assertEquals("Hace 1 día", spanishDateFormatter.timeSince(oneDayAgo.toDate()));

    DateTime oneWeekAgo = now.minusWeeks(1).minusHours(1);
    assertEquals("Hace 1 semana", spanishDateFormatter.timeSince(oneWeekAgo.toDate()));

    DateTime nineMonthsAgo = now.minusMonths(9).minusWeeks(1);
    assertEquals("Hace 9 meses", spanishDateFormatter.timeSince(nineMonthsAgo.toDate()));
  }
  @Test
  public void
      givenKnownOrganizationIdAndTimePeriodWhenQueringStateModificationOfVirtualMachinesThenModificationMustBeAccessibleFromRepositoryInterfaceDuringDefinedTimePeriodAndCertainUptimeTimeSchedulesNeedsBeGiven() {
    long startTimeMilliseconds = System.currentTimeMillis();
    UsageHour usageHour = createUsageHour(startTimeMilliseconds, VirtualMachineState.STOPPED);
    usageHourRepository.store(usageHour);
    UsageHour usageHour0 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STARTED);
    usageHourRepository.store(usageHour0);
    UsageHour usageHour1 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STOPPED);
    usageHourRepository.store(usageHour1);
    UsageHour usageHour2 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STARTED);
    usageHourRepository.store(usageHour2);
    UsageHour usageHour3 = createUsageHour(startTimeMilliseconds, VirtualMachineState.PAUSED);
    usageHourRepository.store(usageHour3);
    UsageHour usageHour4 = createUsageHour(startTimeMilliseconds, VirtualMachineState.RESUMED);
    usageHourRepository.store(usageHour4);
    UsageHour usageHour5 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STOPPED);
    usageHourRepository.store(usageHour5);
    UsageHour usageHour6 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STARTED);
    usageHourRepository.store(usageHour6);
    UsageHour usageHour7 = createUsageHour(startTimeMilliseconds, VirtualMachineState.STOPPED);
    usageHourRepository.store(usageHour7);
    UsageHour usageHour8 = createUsageHour(startTimeMilliseconds, VirtualMachineState.PAUSED);
    usageHourRepository.store(usageHour8);
    UsageHour usageHour9 = createUsageHour(startTimeMilliseconds, VirtualMachineState.RESUMED);
    usageHourRepository.store(usageHour9);
    UsageHour usageHour10 = createUsageHour(startTimeMilliseconds, VirtualMachineState.TERMINATED);
    usageHourRepository.store(usageHour10);

    DateTime startTime = new DateTime(startTimeMilliseconds);
    DateTime endTime = new DateTime(System.currentTimeMillis());
    Collection<UsageHour> usageHours =
        usageHourRepository.loadUsageHoursByOrganizationIdAndUsagePeriod(
            startTimeMilliseconds, startTime.toDate(), endTime.toDate());

    assertEquals(12, usageHours.size());

    UsagePeriod usagePeriod = new UsagePeriod();
    usagePeriod.setUsageHours(usageHours);
    usagePeriod.setStartTime(startTime.toDate());
    usagePeriod.setEndTime(endTime.toDate());
    usagePeriod.loadUptimeHours();

    float uptime = usagePeriod.getUptime();

    System.out.println("Uptime in seconds : " + uptime / 1000);
    System.out.println("Uptime in minutes : " + uptime / 1000 / 60);
    System.out.println("Uptime in hours : " + uptime / 1000 / 60 / 60);
  }
Esempio n. 25
0
  @SuppressWarnings("unchecked")
  @RequestMapping("/importar/web")
  public ModelAndView importarWeb(String pedidoJson, String dataEnvio)
      throws JsonParseException, JsonMappingException, IOException, GeneralSecurityException,
          MessagingException {

    logger.info("===> importarWeb(" + dataEnvio + "): " + pedidoJson);

    ObjectMapper mapper = new ObjectMapper();
    Map<String, String> map = mapper.readValue(pedidoJson, Map.class);

    Pedido pedido = new Pedido();

    pedido.setNomeCliente(map.get("Nome completo"));
    pedido.setEmailMLFormulario(map.get("E-mail cadastrado no MercadoLivre"));
    pedido.setEmailAlternativo(map.get("E-mail alternativo"));
    pedido.setEndereco(map.get("Endereço"));
    pedido.setNumero(map.get("Número"));
    pedido.setComplemento(map.get("Complemento"));
    pedido.setBairro(map.get("Bairro"));
    pedido.setCidade(map.get("Cidade"));
    pedido.setUf(map.get("UF"));

    String cep = tratarCep(map.get("CEP"));
    pedido.setCep(cep);

    pedido.setFormaEnvio(FormaEnvio.getEnum(map.get("Forma de envio")));
    pedido.setItens(map.get("Quais foram os itens e a quantidade adquiridos?"));
    pedido.setTema(map.get("Qual é o tema a ser desenvolvido na arte?"));
    pedido.setCorPredominante(map.get("Qual é a cor predominante da sua arte?"));
    pedido.setMensagem(map.get("Qual a mensagem ou nome a ser personalizado?"));
    pedido.setPossuiFoto("Sim".equalsIgnoreCase(map.get("Deseja colocar alguma fotografia?")));
    pedido.setTelefone(map.get("Qual seu telefone fixo para contato?"));
    pedido.setDetalhes(map.get("Adicione mais detalhes de como você quer a sua personalização"));
    pedido.setUsuarioML(map.get("Usuário ML (não altere este campo)"));

    DateTimeFormatter formatDataEvento = DateTimeFormat.forPattern("YYYYY-MM-dd");
    DateTime dataEvento = formatDataEvento.parseDateTime(map.get("Qual a data do evento?"));
    pedido.setDataEvento(dataEvento.toDate());

    DateTimeFormatter formatDataEnvio = DateTimeFormat.forPattern("dd/MM/YYYY");
    DateTime dataEnvioFormulario = formatDataEnvio.parseDateTime(dataEnvio);
    pedido.setDataEnvioFormulario(dataEnvioFormulario.toDate());

    pedidoService.salvarFormulario(pedido);

    return new ModelAndView("redirect:/pedido/edit/" + pedido.getId());
  }
Esempio n. 26
0
 @Test
 public void shouldNotMakeACallForANonExistentPatient() {
   when(allPatients.get(PATIENT_DOC_ID)).thenReturn(null);
   pillReminderCall.execute(
       PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);
   verify(callService, never()).initiateCall(any(CallRequest.class));
 }
Esempio n. 27
0
  @Test
  public void
      shouldMakeACallForActivePatient_DoesNotRecordDosageAsNotReported_WhenCalledAfterFirstTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();
    TIMES_SENT = 1;

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    pillReminderCall.execute(
        PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService).initiateCall(callRequestArgumentCaptor.capture());
    verifyZeroInteractions(dailyPillReminderAdherenceService);
    verifyZeroInteractions(dailyPillReminderService);
    Map<String, String> payload = callRequestArgumentCaptor.getValue().getPayload();
    assertEquals(
        String.valueOf(TOTAL_TIMES_TO_SEND), payload.get(PillReminderCall.TOTAL_TIMES_TO_SEND));
    assertEquals(String.valueOf(TIMES_SENT), payload.get(PillReminderCall.TIMES_SENT));
    assertEquals(String.valueOf(RETRY_INTERVAL), payload.get(PillReminderCall.RETRY_INTERVAL));
  }
Esempio n. 28
0
  @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);
    }
  }
Esempio n. 29
0
  /**
   * 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);
    }
  }
Esempio n. 30
0
  @Test
  public void shouldMakeACallForActivePatient_AndRecordDosageAsNotReported_WhenCalledFirstTime() {
    String PHONE_NUMBER = "1234567890";
    Patient patient = mock(Patient.class);
    PillRegimen pillRegimen = mock(PillRegimen.class);
    Dose dose = mock(Dose.class);
    DateTime now = DateUtil.now();

    when(patient.allowAdherenceCalls()).thenReturn(true);
    when(patient.getMobilePhoneNumber()).thenReturn(PHONE_NUMBER);
    when(allPatients.get(PATIENT_DOC_ID)).thenReturn(patient);

    when(dailyPillReminderService.getPillRegimen(anyString())).thenReturn(pillRegimen);
    when(pillRegimen.getDoseAt(Matchers.<DateTime>any())).thenReturn(dose);
    when(pillRegimen.getId()).thenReturn("pillRegimenId");
    when(dose.getDoseTime()).thenReturn(now);

    pillReminderCall.execute(
        PATIENT_DOC_ID, NOW.toDate(), TIMES_SENT, TOTAL_TIMES_TO_SEND, RETRY_INTERVAL);

    ArgumentCaptor<CallRequest> callRequestArgumentCaptor =
        ArgumentCaptor.forClass(CallRequest.class);
    verify(callService).initiateCall(callRequestArgumentCaptor.capture());
    verify(dailyPillReminderAdherenceService)
        .recordDosageAdherenceAsNotCaptured(
            PATIENT_DOC_ID, "pillRegimenId", dose, DosageStatus.NOT_RECORDED, now);
    Map<String, String> payload = callRequestArgumentCaptor.getValue().getPayload();
    assertEquals(
        String.valueOf(TOTAL_TIMES_TO_SEND), payload.get(PillReminderCall.TOTAL_TIMES_TO_SEND));
    assertEquals(String.valueOf(TIMES_SENT), payload.get(PillReminderCall.TIMES_SENT));
    assertEquals(String.valueOf(RETRY_INTERVAL), payload.get(PillReminderCall.RETRY_INTERVAL));
  }