Example usage for org.joda.time DateTime withTime

List of usage examples for org.joda.time DateTime withTime

Introduction

In this page you can find the example usage for org.joda.time DateTime withTime.

Prototype

public DateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) 

Source Link

Document

Returns a copy of this datetime with the specified time, retaining the date fields.

Usage

From source file:au.org.intersect.dms.bookinggw.impl.DateUtils.java

License:Open Source License

/**
 * Returns given date with zero time//from  ww w .j  av a  2 s  .  c o  m
 * 
 * @param date date to truncate time
 * @return
 */
public static Date getFromDate(Date date) {
    DateTime dateTime = new DateTime(date);
    DateTime fromDate = dateTime.withTime(0, 0, 0, 0);
    return fromDate.toDate();
}

From source file:au.org.intersect.dms.bookinggw.impl.DateUtils.java

License:Open Source License

/**
 * Return given date with time set to 23:59:59
 * /*w  w  w.  ja  va2  s  . c  om*/
 * @param date date to round time
 * @return
 */
public static Date getToDate(Date date) {
    DateTime dateTime = new DateTime(date);
    DateTime toDate = dateTime.withTime(DAY_END_HOUR, DAY_END_MINUTES, DAY_END_SECONDS, 0);
    return toDate.toDate();
}

From source file:azkaban.webapp.servlet.ScheduleServlet.java

License:Apache License

private void ajaxLoadHistory(HttpServletRequest req, HttpServletResponse resp, User user)
        throws ServletException, IOException {
    resp.setContentType(JSON_MIME_TYPE);
    long today = DateTime.now().withTime(0, 0, 0, 0).getMillis();
    long startTime = getLongParam(req, "startTime");
    DateTime start = new DateTime(startTime);
    // Ensure start time is 12:00 AM
    startTime = start.withTime(0, 0, 0, 0).getMillis();
    boolean useCache = false;
    if (startTime < today) {
        useCache = true;//from  w  w  w .  j  a  va  2s  .  co m
    }
    long endTime = startTime + 24 * 3600 * 1000;
    int loadAll = getIntParam(req, "loadAll");

    // Cache file
    String cacheDir = getApplication().getServerProps().getString("cache.directory", "cache");
    File cacheDirFile = new File(cacheDir, "schedule-history");
    File cache = new File(cacheDirFile, startTime + ".cache");
    cache.getParentFile().mkdirs();

    if (useCache) {
        // Determine if cache exists
        boolean cacheExists = false;
        synchronized (this) {
            cacheExists = cache.exists() && cache.isFile();
        }
        if (cacheExists) {
            // Send the cache instead
            InputStream cacheInput = new BufferedInputStream(new FileInputStream(cache));
            try {
                IOUtils.copy(cacheInput, resp.getOutputStream());
                return;
            } finally {
                IOUtils.closeQuietly(cacheInput);
            }
        }
    }

    // Load data if not cached
    List<ExecutableFlow> history = null;
    try {
        AzkabanWebServer server = (AzkabanWebServer) getApplication();
        ExecutorManagerAdapter executorManager = server.getExecutorManager();
        history = executorManager.getExecutableFlows(null, null, null, 0, startTime, endTime, -1, -1);
    } catch (ExecutorManagerException e) {
        logger.error(e);
    }

    HashMap<String, Object> ret = new HashMap<String, Object>();
    List<HashMap<String, Object>> output = new ArrayList<HashMap<String, Object>>();
    ret.put("items", output);
    for (ExecutableFlow historyItem : history) {
        // Check if it is an scheduled execution
        if (historyItem.getScheduleId() >= 0 || loadAll != 0) {
            writeHistoryData(output, historyItem);
        }
    }

    // Make sure we're ready to cache it, otherwise output and return
    synchronized (this) {
        if (!useCache || cache.exists()) {
            JSONUtils.toJSON(ret, resp.getOutputStream(), false);
            return;
        }
    }

    // Create cache file
    File cacheTemp = new File(cacheDirFile, startTime + ".tmp");
    cacheTemp.createNewFile();
    OutputStream cacheOutput = new BufferedOutputStream(new FileOutputStream(cacheTemp));
    try {
        OutputStream outputStream = new SplitterOutputStream(cacheOutput, resp.getOutputStream());
        // Write to both the cache file and web output
        JSONUtils.toJSON(ret, outputStream, false);
    } finally {
        IOUtils.closeQuietly(cacheOutput);
    }
    // Move cache file
    synchronized (this) {
        cacheTemp.renameTo(cache);
    }
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Gets customers by club id.//  w w  w  .ja  va 2  s.  c  om
 *
 * @param id        the id
 * @param yearMonth the year month
 * @param response  the response
 * @return the customers by club id
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs/{id}/customers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<User>> getCustomersByClubId(@PathVariable Long id, @RequestParam String yearMonth,
        HttpServletResponse response) throws URISyntaxException {
    log.debug("REST request to get Actions by club id : {}", id);

    List<User> users = new ArrayList<User>();
    List<ReservationHistory> reservationHistories = null;

    if (StringUtils.isNotEmpty(yearMonth)) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyMM");
        DateTime monthStartDate = formatter.parseDateTime(yearMonth);
        DateTime monthEndDate = monthStartDate.dayOfMonth().withMaximumValue();
        monthEndDate = monthEndDate.withTime(23, 59, 59, 59);
        reservationHistories = reservationHistoryRepository.findByClubIdAndUsedAndStartTimeBetween(id, true,
                monthStartDate, monthEndDate);
    } else {
        reservationHistories = reservationHistoryRepository.findByClubIdAndUsed(id, true);
    }

    if (reservationHistories == null || reservationHistories.isEmpty()) {
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

    Set<Long> userIds = new HashSet<>();
    for (ReservationHistory history : reservationHistories) {
        userIds.add(history.getUserId());
    }

    users = userRepository.findAll(userIds);

    return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}

From source file:com.facebook.presto.atop.AtopSplitManager.java

License:Apache License

@Override
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session,
        ConnectorTableLayoutHandle layoutHandle) {
    AtopTableLayoutHandle handle = checkType(layoutHandle, AtopTableLayoutHandle.class, "layoutHandle");

    AtopTableHandle table = handle.getTableHandle();

    List<ConnectorSplit> splits = new ArrayList<>();
    DateTime end = DateTime.now().withZone(timeZone);
    for (Node node : nodeManager.getActiveDatasourceNodes(connectorId.getId())) {
        DateTime start = end.minusDays(maxHistoryDays - 1).withTimeAtStartOfDay();
        while (start.isBefore(end)) {
            DateTime splitEnd = start.withTime(23, 59, 59, 999);
            Domain splitDomain = Domain.create(
                    ValueSet.ofRanges(//www .j  a v  a 2 s  . co m
                            Range.range(TIMESTAMP, start.getMillis(), true, splitEnd.getMillis(), true)),
                    false);
            if (handle.getStartTimeConstraint().overlaps(splitDomain)
                    && handle.getEndTimeConstraint().overlaps(splitDomain)) {
                splits.add(new AtopSplit(table.getTable(), node.getHostAndPort(), start));
            }
            start = start.plusDays(1).withTimeAtStartOfDay();
        }
    }

    return new FixedSplitSource(connectorId.getId(), splits);
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private List<NewTaskRequestDto> createTasksForVariableContinuousInfusion(final String patientId,
        final VariableComplexTherapyDto therapy, final Interval taskCreationInterval,
        final AdministrationTaskCreateActionEnum action, final DateTime lastTaskTimestamp,
        final DateTime actionTimestamp) {
    final DateTime therapyStart = therapy.getStart();

    final Map<HourMinuteDto, TherapyDoseDto> timesWithDosesMap = getTimesDosesMapForVariableTherapies(therapy);

    final HourMinuteDto lastChangeHourMinute = Iterables.getLast(timesWithDosesMap.keySet());

    final boolean isTwoDayInfusion = therapyStart.isAfter(
            therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0));
    final DateTime lastChangeTime = isTwoDayInfusion
            ? therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0)
                    .plusDays(1)/*from  www .j  av  a  2 s. c o  m*/
            : therapyStart.withTime(lastChangeHourMinute.getHour(), lastChangeHourMinute.getMinute(), 0, 0);

    final HourMinuteDto firstChangeHourMinute = Iterables.getFirst(timesWithDosesMap.keySet(), null);

    final List<NewTaskRequestDto> taskRequests = new ArrayList<>();

    //noinspection OverlyComplexBooleanExpression
    final boolean createStartTask = action == AdministrationTaskCreateActionEnum.PRESCRIBE
            || action == AdministrationTaskCreateActionEnum.MODIFY_BEFORE_START
            || action == AdministrationTaskCreateActionEnum.PREVIEW_TIMES_ON_NEW_PRESCRIPTION
            || action == AdministrationTaskCreateActionEnum.MODIFY
            || (action == AdministrationTaskCreateActionEnum.AUTO_CREATE && lastTaskTimestamp == null);

    if (createStartTask) {
        final TherapyDoseDto dose = timesWithDosesMap.get(firstChangeHourMinute);

        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.START, therapyStart, dose);
        taskRequests.add(startTaskRequest);
    } else if (action == AdministrationTaskCreateActionEnum.REISSUE) {
        final TherapyDoseDto dose;
        final DateTime restartTime;
        if (actionTimestamp.isBefore(therapyStart)) {
            dose = timesWithDosesMap.get(firstChangeHourMinute);
            restartTime = therapyStart;
        } else if (actionTimestamp.isAfter(lastChangeTime)) {
            dose = timesWithDosesMap.get(lastChangeHourMinute);
            restartTime = actionTimestamp;
        } else {
            dose = getPreviousAdministrationTimeWithDose(actionTimestamp, timesWithDosesMap, true).getSecond();
            restartTime = actionTimestamp;
        }
        final NewTaskRequestDto startTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.START, restartTime, dose);
        taskRequests.add(startTaskRequest);
    }

    Pair<DateTime, TherapyDoseDto> nextTimeWithDose = getNextAdministrationTimeWithDose(action, therapy,
            therapyStart, timesWithDosesMap, false);

    while (!nextTimeWithDose.getFirst().isAfter(taskCreationInterval.getEnd())
            && !nextTimeWithDose.getFirst().isAfter(lastChangeTime)) {
        if (nextTimeWithDose.getFirst().isAfter(taskCreationInterval.getStart())) {
            taskRequests
                    .add(createMedicationTaskRequest(patientId, therapy, AdministrationTypeEnum.ADJUST_INFUSION,
                            nextTimeWithDose.getFirst(), nextTimeWithDose.getSecond()));
        }
        nextTimeWithDose = getNextAdministrationTimeWithDose(action, therapy, nextTimeWithDose.getFirst(),
                timesWithDosesMap, false);
    }

    final DateTime therapyEnd = therapy.getEnd();
    if (therapyEnd != null && !therapyEnd.isAfter(taskCreationInterval.getEnd())) {
        final NewTaskRequestDto endTaskRequest = createMedicationTaskRequest(patientId, therapy,
                AdministrationTypeEnum.STOP, therapyEnd, null);
        taskRequests.add(endTaskRequest);
    }
    return taskRequests;
}

From source file:com.onboard.web.api.activity.ActivityApiController.java

License:Apache License

@RequestMapping(value = "/activities", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class })
@ResponseBody//w  ww  .  j a v  a2  s .c  o m
public CompanyActivities showActivities(@PathVariable int companyId,
        @RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until,
        @RequestParam(required = false) Integer userId, @RequestParam(required = false) Integer projectId,
        @RequestParam(required = false) String type) {
    DateTime dt = until == null ? new DateTime() : new DateTime(until);
    until = dt.withTime(0, 0, 0, 0).plusDays(1).plusMillis(-1).toDate();
    boolean hasNext = false;
    Date nextDay = null;

    List<Activity> activities = activityService.getUserVisibleTillDay(companyId, userId, projectId, until, type,
            LIMIT);

    if (activities.size() > 0) {

        Activity activity = activities.get(activities.size() - 1);
        nextDay = new DateTime(activity.getCreated()).withTime(0, 0, 0, 0).plusMillis(-1).toDate();

        // ?nextDay??hasNexttrue
        List<Activity> nextActivities = activityService.getUserVisibleTillDay(companyId, userId, projectId,
                nextDay, type, LIMIT);

        if (nextActivities.size() > 0) {
            hasNext = true;
        }
    }
    return new CompanyActivities(activities, hasNext, nextDay);
}

From source file:com.onboard.web.api.user.UserAPIController.java

License:Apache License

@RequestMapping(value = "/{companyId}/user/{userId}/activities", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody//w w w .j a va2  s .  co m
public Map<String, Object> viewUserActivities(@PathVariable int companyId, @PathVariable int userId,
        @RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until,
        Model model) {

    Builder<String, Object> builder = ImmutableMap.builder();

    DateTime dt = until == null ? new DateTime() : new DateTime(until);
    until = dt.withTime(0, 0, 0, 0).plusDays(1).plusMillis(-1).toDate();
    List<Integer> projectList = getProjectListOfCurrentUser(companyId);
    TreeMap<Date, List<Activity>> map = activityService.getByUserGroupByDate(companyId, userId,
            ACTIVITY_PER_PAGE, projectList, until);

    TreeMap<String, List<ActivityDTO>> mapDTO = makeMapSerilizable(map);
    builder.put("activities", mapDTO);
    boolean hasNext = false;

    if (map != null && map.size() > 0) {
        Date newUntil = new DateTime(map.lastKey()).plusDays(-1).withTime(0, 0, 0, 0).toDate();
        TreeMap<Date, List<Activity>> nextMap = activityService.getByUserGroupByDate(companyId, userId,
                ACTIVITY_PER_PAGE, projectList, newUntil);
        hasNext = nextMap != null;
        builder.put("nextPage", dtf.print(new DateTime(newUntil)));
    }
    builder.put("hasNext", hasNext);

    return builder.build();
}

From source file:com.onboard.web.api.user.UserAPIController.java

License:Apache License

/**
 * /*  w ww  . j a  v  a 2 s  .  co m*/
 * 
 * @param companyId
 * @param userId
 * @param until
 * @param model
 * @return
 */
@RequestMapping(value = "/{companyId}/user/{userId}/attachments", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody
public ImmutableMap<String, ?> viewUserAttachments(@PathVariable int companyId, @PathVariable int userId,
        @RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until,
        @RequestParam(value = "page", required = false, defaultValue = "1") Integer page) {

    Builder<String, Object> builder = ImmutableMap.builder();

    DateTime dt = until == null ? new DateTime() : new DateTime(until);
    until = dt.withTime(0, 0, 0, 0).plusDays(1).plusMillis(-1).toDate();
    List<Integer> projectList = getProjectListOfCurrentUser(companyId);

    TreeMap<Date, List<Attachment>> map = attachmentService.getAttachmentsByUserGroupByDate(companyId, userId,
            projectList, until, PER_PAGE);
    TreeMap<String, List<AttachmentDTO>> mapDTO = makeUserAttachmentsMapSerilizable(map);
    builder.put("userAttachments", mapDTO);

    // UserDTO userDto = new UserDTO(userService.getUserById(userId));
    boolean hasNext = false;
    if (map != null && map.size() > 0) {
        Date newUntil = new DateTime(map.lastKey()).withTime(0, 0, 0, 0).plusMillis(-1).toDate();
        TreeMap<Date, List<Attachment>> nextMap = attachmentService.getAttachmentsByUserGroupByDate(companyId,
                userId, projectList, newUntil, PER_PAGE);
        hasNext = nextMap.size() > 0;

        builder.put("nextPage", dtf.print(new DateTime(newUntil)));
    }
    builder.put("hasNext", hasNext);

    return builder.build();
}

From source file:com.onboard.web.api.user.UserAPIController.java

License:Apache License

/**
 * ?todo//from w  w  w .  ja v a2  s.  c o  m
 * 
 * @param companyId
 * @param userId
 * @param model
 * @return
 */
@RequestMapping(value = "/{companyId}/user/{userId}/completed_todos", method = RequestMethod.GET)
@Interceptors({ CompanyMemberRequired.class, UserChecking.class })
@ResponseBody
public Map<String, Object> viewUserCompletedTodos(@PathVariable int companyId, @PathVariable int userId,
        @RequestParam(value = "until", required = false) @DateTimeFormat(iso = ISO.DATE) Date until,
        Model model) {
    Builder<String, Object> builder = ImmutableMap.builder();
    DateTime dt = until == null ? new DateTime() : new DateTime(until);
    until = dt.withTime(0, 0, 0, 0).plusDays(1).plusMillis(-1).toDate();
    List<Integer> projectList = getProjectListOfCurrentUser(companyId);

    TreeMap<Date, List<Todolist>> map = todoService.getCompletedTodolistsGroupByDateByUser(companyId, userId,
            projectList, until, PER_PAGE);
    TreeMap<String, List<TodolistDTO>> mapDTO = makeUserCompletedTodosMapSerilizable(map);
    builder.put("completedTodos", mapDTO);
    Map<Integer, String> projectIdToName = getProjectIdAndNameByCompanyId(companyId);
    builder.put("projectsName", projectIdToName);

    boolean hasNext = false;

    if (map != null && map.size() > 0) {
        Date newUntil = new DateTime(map.lastKey()).withTime(0, 0, 0, 0).plusMillis(-1).toDate();

        TreeMap<Date, List<Todolist>> nextMap = todoService.getCompletedTodolistsGroupByDateByUser(companyId,
                userId, projectList, newUntil, PER_PAGE);
        hasNext = nextMap.size() > 0;
        builder.put("nextPage", dtf.print(new DateTime(newUntil)));
    }

    builder.put("hasNext", hasNext);

    return builder.build();
}