Java Code Examples for org.joda.time.DateTime.now()

The following are Jave code examples for showing how to use now() of the org.joda.time.DateTime class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: exam   File: EnrolmentControllerTest.java   Source Code and License Vote up 6 votes
@Test
@RunAsStudent
public void testCreateEnrolmentPastReservationExists() throws Exception {
    // Setup
    reservation.setMachine(room.getExamMachines().get(0));
    reservation.setStartAt(DateTime.now().minusDays(2));
    reservation.setEndAt(DateTime.now().minusDays(1));
    reservation.save();
    DateTime enrolledOn = DateTime.now();
    enrolment.setEnrolledOn(enrolledOn);
    enrolment.setReservation(reservation);
    enrolment.save();

    // Execute
    Result result = request(Helpers.POST,
            String.format("/app/enroll/%s/exam/%d", exam.getCourse().getCode(), exam.getId()), null);
    assertThat(result.status()).isEqualTo(200);

    // Verify
    List<ExamEnrolment> enrolments = Ebean.find(ExamEnrolment.class).findList();
    assertThat(enrolments).hasSize(2);
    ExamEnrolment e = enrolments.get(1);
    assertThat(e.getEnrolledOn().isAfter(enrolledOn));
    assertThat(e.getReservation()).isNull();
}
 
Example 2
Project: verify-matching-service-adapter   File: UserAccountCreationAttributeExtractorTest.java   Source Code and License Vote up 6 votes
@Test
public void shouldReturnRequiredCycle3AttributesWhenValuesExistInCycle3Assertion(){
    List<Attribute> accountCreationAttributes = Arrays.asList(CYCLE_3).stream()
            .map(attributeQueryAttributeFactory::createAttribute)
            .collect(toList());

    ImmutableMap<String, String> build = ImmutableMap.<String, String>builder().put("cycle3Key", "cycle3Value").build();
    Cycle3Dataset cycle3Dataset = Cycle3Dataset.createFromData(build);
    HubAssertion hubAssertion =new HubAssertion("1", "issuerId", DateTime.now(), new PersistentId("1"), null, Optional.of(cycle3Dataset));

    List<Attribute> userAttributesForAccountCreation = userAccountCreationAttributeExtractor.getUserAccountCreationAttributes(accountCreationAttributes, null, Optional.of(hubAssertion));

    List<Attribute> cycle_3 = userAttributesForAccountCreation.stream().filter(a -> a.getName().equals("cycle_3")).collect(toList());
    StringBasedMdsAttributeValue personName = (StringBasedMdsAttributeValue) cycle_3.get(0).getAttributeValues().get(0);

    assertThat(cycle_3.size()).isEqualTo(1);
    assertThat(personName.getValue().equals("cycle3Value"));
}
 
Example 3
Project: verify-service-provider   File: InstantValidator.java   Source Code and License Vote up 6 votes
public void validate(DateTime instant, String instantName) {
    Duration age = new Duration(instant, DateTime.now());
    if (age.isLongerThan(MAXIMUM_INSTANT_AGE)) {
        throw new SamlResponseValidationException(String.format("%s is too far in the past %s",
            instantName,
            PeriodFormat.getDefault().print(age.toPeriod()))
        );
    }

    if (dateTimeComparator.isAfterNow(instant)) {
        throw new SamlResponseValidationException(String.format("%s is in the future %s",
            instantName,
            instant.withZone(UTC).toString(dateHourMinuteSecond()))
        );
    }
}
 
Example 4
Project: cat-is-a-dog   File: TodoHabitDataSource.java   Source Code and License Vote up 6 votes
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    DateTime now = DateTime.now();

    dueHabits.clear();

    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        HabitDataModel model = snapshot.getValue(HabitDataModel.class);

        if (model != null) {
            Habit habit = model.getHabit();
            if (habit != null) {
                dueHabits.add(habit);
            }
        }
    }

    recreateDataset();
}
 
Example 5
Project: verify-hub   File: RpErrorResponseGeneratorService.java   Source Code and License Vote up 6 votes
public SamlMessageDto generate(RequestForErrorResponseFromHubDto requestForErrorResponseFromHubDto) {

        try {
            final OutboundResponseFromHub response = new OutboundResponseFromHub(
                    requestForErrorResponseFromHubDto.getResponseId(),
                    requestForErrorResponseFromHubDto.getInResponseTo(),
                    hubEntityId,
                    DateTime.now(),
                    TransactionIdaStatus.valueOf(requestForErrorResponseFromHubDto.getStatus().name()),
                    empty(),
                    requestForErrorResponseFromHubDto.getAssertionConsumerServiceUri());

            final String errorResponse = outboundResponseFromHubToResponseTransformerFactory.get(requestForErrorResponseFromHubDto.getAuthnRequestIssuerEntityId()).apply(response);

            return new SamlMessageDto(errorResponse);
        } catch (Exception e) {
            throw new UnableToGenerateSamlException("Unable to generate RP error response", e, Level.ERROR);
        }

    }
 
Example 6
Project: yum   File: FoodsApiControllerTest.java   Source Code and License Vote up 5 votes
@Test
@WithMockAuth(id="1")
public void testFoodsPostOk() throws Exception {
    
    Food mockFoodOk = new Food(0, "Pastitsio", new ArrayList<>(), FoodType.MAIN, "test Pastitsio", new BigDecimal("5.65"), false, null, true);         
    Settings global_settings = new Settings(1, LocalTime.MIDNIGHT,  DateTime.now(), "", "", "", "", 0, 1, "", "");
    
    
    given(settingsRepo.findOne(1)).willReturn(global_settings); 
    given(mockFoodRepository.findByNameAndArchived(mockFoodOk.getName(), false)).willReturn(null);
    
    mockMvc.perform(post("/api/foods").content(
    "{\n" +
    "  \"foodName\": \""+mockFoodOk.getName()+"\",\n" +
    "  \"foodType\": \""+foodType.convertToDatabaseColumn(mockFoodOk.getFoodType())+"\",\n" +
    "  \"description\": \""+mockFoodOk.getDescription()+"\",\n" +
    "  \"standard\": \""+mockFoodOk.isStandard()+"\",\n" +
    "  \"price\": "+mockFoodOk.getPrice()+"\n" +
   
    "}"
    ).contentType(MediaType.APPLICATION_JSON_UTF8))
        .andExpect(status().isNoContent());
    
    
    verify(mockFoodRepository, times(1)).findByNameAndArchived(mockFoodOk.getName(), false);
    verify(mockFoodRepository, times(1)).save(mockFoodOk);
    verifyNoMoreInteractions(mockFoodRepository);
 
}
 
Example 7
Project: Reer   File: DurationMeasurementImpl.java   Source Code and License Vote up 5 votes
@Override
public void stop() {
    DateTime end = DateTime.now();
    long endNanos = System.nanoTime();
    measuredOperation.setStart(start);
    measuredOperation.setEnd(end);
    measuredOperation.setTotalTime(Duration.millis((endNanos - startNanos) / 1000000L));
}
 
Example 8
Project: Biliomi   File: SpotifyApiImpl.java   Source Code and License Vote up 5 votes
/**
 * Update the persisted access token and the authorization header if necessary
 *
 * @return The id of the currently linked user
 */
@SuppressWarnings("Duplicates")
private synchronized String executeTokenPreflight() throws Exception {
  AuthToken token = authTokenDao.get(TokenGroup.INTEGRATIONS, "spotify");

  if (StringUtils.isEmpty(token.getToken())) {
    throw new UnavailableException("The Spotify Api is not connected to an account");
  }

  DateTime expiryTime = token.getExpiryTime();
  DateTime now = DateTime.now();
  if (expiryTime != null && now.isAfter(expiryTime)) {
    SpotifyOAuthFlowDirector director = new SpotifyOAuthFlowDirector(configService.getConsumerKey(), configService.getConsumerSecret(), webClient);
    boolean refreshSuccess = director.awaitRefreshedAccessToken(token.getRefreshToken());

    if (refreshSuccess) {
      token.setToken(director.getAccessToken());
      token.setIssuedAt(now);
      token.setTimeToLive(director.getTimeToLive());
      authTokenDao.save(token);
    } else {
      throw new UnavailableException("The Spotify Api failed to refresh the access token");
    }
  } else {
    headers.put(HttpHeader.AUTHORIZATION, OAUTH_HEADER_PREFIX + token.getToken());
  }
  return token.getUserId();
}
 
Example 9
Project: NoraUi   File: CucumberHooksUT.java   Source Code and License Vote up 5 votes
@Before
public void setUp() throws InterruptedException {
    DateTime now = DateTime.now();
    // prepare mock
    mockDataInputProvider = Mockito.mock(ExcelDataProvider.class);
    PowerMockito.mockStatic(Context.class);
    when(Context.getDataInputProvider()).thenReturn(mockDataInputProvider);
    when(Context.getStartCurrentScenario()).thenReturn(now);
    DateTimeUtils.setCurrentMillisFixed(now.plusSeconds(5).getMillis());
}
 
Example 10
Project: FinalProject   File: NotificationCardViewHolder.java   Source Code and License Vote up 5 votes
public void bind(NotificationPojo dataItem) {
    this.dataItem = dataItem;

    if (dataItem.getUsername() != null){
        if(dataItem.getUsername().trim().isEmpty()){
            personName.setText("Anonymous");
        } else {
            personName.setText(dataItem.getUsername());
        }
    }

    DateTime now = DateTime.now();
    String timeInMills= String.valueOf(System.currentTimeMillis());
    String currentTimeDirect = String.valueOf(Long.parseLong(dataItem.getTime().trim()));
    int currentTime = (int) (System.currentTimeMillis() - Long.parseLong(dataItem.getTime().trim()))/1000;

    // Todo Write the logic to get activity as per the feeling name
    notificationTime.setText(CurrentTimeLong.getCurrentTime(dataItem.getTime().trim(), itemView.getContext()));

    if (dataItem.getTextStatus() != null){
        if (!(dataItem.getTextStatus().trim().isEmpty())){
            notification_feeling_status.setText(String.valueOf(getEmotionValue(dataItem) + " your post: " + dataItem.getTextStatus().trim()));
        } else {
            notification_feeling_status.setText("No status");
        }
    }

    personPhoto.setImageURI(dataItem.getAvatarPic());
}
 
Example 11
Project: verify-hub   File: HubAttributeQueryRequestBuilder.java   Source Code and License Vote up 5 votes
public HubAttributeQueryRequest createHubAttributeQueryRequest(final AttributeQueryRequestDto attributeQueryRequestDto) {
    return new HubAttributeQueryRequest(
            attributeQueryRequestDto.getRequestId(),
            new PersistentId(attributeQueryRequestDto.getPersistentId().getNameId()),
            attributeQueryRequestDto.getEncryptedMatchingDatasetAssertion(),
            attributeQueryRequestDto.getAuthnStatementAssertion(),
            createCycle3Assertion(attributeQueryRequestDto),
            attributeQueryRequestDto.getUserAccountCreationAttributes(),
            DateTime.now(),
            attributeQueryRequestDto.getAssertionConsumerServiceUri(),
            attributeQueryRequestDto.getAuthnRequestIssuerEntityId(),
            AuthnContext.valueOf(attributeQueryRequestDto.getLevelOfAssurance().name()),
            hubEntityId);
}
 
Example 12
Project: mobile-app-dev-book   File: JournalViewActivity.java   Source Code and License Vote up 5 votes
private File createFileName(String prefix, String ext) throws
        IOException {
    DateTime now = DateTime.now();
    DateTimeFormatter fmt = DateTimeFormat.forPattern
            ("yyyyMMdd-HHmmss");
    File cacheDir = getExternalCacheDir();
    File media = File.createTempFile(prefix + "-" + fmt.print(now),
            ext, cacheDir);
    return media;
}
 
Example 13
Project: Android_watch_magpie   File: MagpieFragment.java   Source Code and License Vote up 5 votes
@Override
public void onDateSet(CalendarDatePickerDialog calendarDatePickerDialog,
                      int year, int monthOfYear, int dayOfMonth) {
    FragmentManager fm = ((PublisherActivity) getActivity()).getSupportFragmentManager();
    timestamp.setDate(year, monthOfYear + 1, dayOfMonth);
    DateTime now = DateTime.now();
    RadialTimePickerDialog radialTimePickerDialog = RadialTimePickerDialog
            .newInstance(this, now.getHourOfDay(), now.getMinuteOfHour(), true);
    radialTimePickerDialog.show(fm, FRAG_TAG_TIME_PICKER);

}
 
Example 14
Project: verify-hub   File: MatchingServiceHealthcheckRequestGeneratorService.java   Source Code and License Vote up 5 votes
public SamlMessageDto generate(MatchingServiceHealthCheckerRequestDto dto) {
    MatchingServiceHealthCheckRequest matchingServiceRequest = new MatchingServiceHealthCheckRequest(
            MessageFormat.format("healthcheck-request-{0}", UUID.randomUUID().toString()),
            DateTime.now(),
            new PersistentId("healthcheck-pid"),
            URI.create(""),
            dto.getTransactionEntityId(),
            hubEntityId
    );

    return attributeQueryGenerator.createAttributeQueryContainer(matchingServiceRequest, dto.getMatchingServiceEntityId());
}
 
Example 15
Project: crockpod   File: Alarm.java   Source Code and License Vote up 5 votes
public DateTime getNextTriggerTime() {
    DateTime now = DateTime.now();
    DateTime target = now
            .withHourOfDay(getHourOfDay())
            .withMinuteOfHour(getMinute())
            .withSecondOfMinute(0)
            .withMillisOfSecond(0);

    return target.isBefore(now) ? target.plus(REPEAT_DURATION) : target;
}
 
Example 16
Project: WebAutomation_AllureParallel   File: DateAndTime.java   Source Code and License Vote up 4 votes
public static int getYear() throws Exception 
{
	DateTime datetime = DateTime.now();
	int year = datetime.getYear();
	return year;
}
 
Example 17
Project: WebAutomation_AllureParallel   File: DateAndTime.java   Source Code and License Vote up 4 votes
public static int getMonth_Integer() throws Exception 
{
	DateTime datetime = DateTime.now();
	int month = datetime.getMonthOfYear();
	return month;
}
 
Example 18
Project: Fahrplan   File: DepartureArrivalModel.java   Source Code and License Vote up 4 votes
public DepartureArrivalModel() {
    selectedDateTime = DateTime.now();
    departure = true;
}
 
Example 19
Project: WebAutomation_AllureParallel   File: DateAndTime.java   Source Code and License Vote up 4 votes
public static String getMinuteOfTheHourAsString() throws Exception 
{
	DateTime datetime = DateTime.now();
	String minuteOfTheHour = datetime.minuteOfHour().getAsText();
	return minuteOfTheHour;
}
 
Example 20
Project: powsybl-core   File: MpiJobSchedulerImpl.java   Source Code and License Vote up 4 votes
private boolean startTasks(MpiJob job) throws IOException, InterruptedException {
        long t0 = System.currentTimeMillis();
        try {
            CommandExecution execution = job.getExecution();
            Command command = execution.getCommand();

            int taskIndex = job.getTaskIndex();

            if (taskIndex < execution.getExecutionCount()) {
                // reserve one core for each of the execution instances
                List<Core> allocatedCores = resources.reserveCores(execution.getExecutionCount() - taskIndex, job.getUsedRanks());
                if (allocatedCores != null && !allocatedCores.isEmpty()) {

                    if (taskIndex == 0) {
                        statistics.logJobStart(job.getId(), command.getId(), execution.getTags());
                    }

                    LOGGER.debug("Sending commands {} to slaves {} using working directory {}",
                            command.toString(-1), allocatedCores, job.getWorkingDir());

                    DateTime startTime = DateTime.now();

                    // encode task messages
                    int oldTaskIndex = taskIndex;
                    List<MpiTask> tasks = new ArrayList<>(allocatedCores.size());
                    for (Core core : allocatedCores) {
                        byte[] message = createTaskMessage(job, core.rank, command, taskIndex).toByteArray();

                        MpiTask task = new MpiTask(taskId++, core, taskIndex, message, startTime);
                        tasks.add(task);

                        statistics.logTaskStart(task.getId(),
                                                job.getId(),
                                                taskIndex,
                                                startTime,
                                                core.rank.num,
                                                core.thread,
                                                message.length);

                        taskIndex++;

                        // update used ranks
                        // TODO c'est completement bugge, ne pas reactiver!!!!
//                        job.getUsedRanks().add(core.rank.num);
                    }

                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Starting tasks {} of job {}",
                                tasks.stream().map(MpiTask::getIndex).collect(Collectors.toList()), job.getId());
                    }

                    // run tasks on slaves nodes
                    long t1 = System.currentTimeMillis();
                    try {
                        nativeServices.startTasks(tasks);
                    } finally {
                        startTasksJniTime += System.currentTimeMillis() - t1;
                    }

                    startedTasks.addAndGet(allocatedCores.size());

                    job.setTaskIndex(taskIndex);
                    job.getRunningTasks().addAll(tasks);

                    // notify execution start
                    try {
                        job.getListener().onExecutionStart(oldTaskIndex, taskIndex);
                    } catch (Exception e) {
                        LOGGER.error(e.toString(), e);
                    }
                    return false;
                }
            }
            return true;
        } finally {
            startTasksTime += System.currentTimeMillis() - t0;
        }
    }