Example usage for org.joda.time DateTime plusMinutes

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

Introduction

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

Prototype

public DateTime plusMinutes(int minutes) 

Source Link

Document

Returns a copy of this datetime plus the specified number of minutes.

Usage

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

License:Open Source License

private List<NewTaskRequestDto> createTasksForVariableComplexTherapy(final String patientId,
        final VariableComplexTherapyDto therapy, final Interval taskCreationInterval,
        final Map<HourMinuteDto, TherapyDoseDto> timesWithDosesMap,
        final AdministrationTaskCreateActionEnum action) {
    final List<TimedComplexDoseElementDto> timedDoseElements = therapy.getTimedDoseElements();
    final List<NewTaskRequestDto> taskRequests = new ArrayList<>();
    if (!timesWithDosesMap.isEmpty()) {
        Pair<DateTime, TherapyDoseDto> next = getNextAdministrationTimeWithDose(action, therapy,
                taskCreationInterval.getStart(), timesWithDosesMap,
                action.isTaskCreationIntervalStartIncluded());

        DateTime nextTaskTime = next.getFirst();

        if (action == AdministrationTaskCreateActionEnum.REISSUE) // move on to first next START task in taskCreationInterval
        {//from  ww  w. jav a2  s .  c o  m
            while (!isFirstPrescribedComplexDoseElement(timedDoseElements, nextTaskTime)) {
                next = getNextAdministrationTimeWithDose(AdministrationTaskCreateActionEnum.REISSUE, therapy,
                        nextTaskTime, timesWithDosesMap, false);

                nextTaskTime = next.getFirst();
            }
        }

        final Map<HourMinuteDto, Integer> durations = therapy.getTimedDoseElements().stream().collect(Collectors
                .toMap(TimedComplexDoseElementDto::getDoseTime, d -> d.getDoseElement().getDuration()));

        final boolean preview = action == AdministrationTaskCreateActionEnum.PREVIEW_TIMES_ON_NEW_PRESCRIPTION;
        String groupUUId = null;
        while (!isAfterTherapyEnd(therapy, nextTaskTime)) {
            final boolean isFirst = isFirstPrescribedComplexDoseElement(timedDoseElements, nextTaskTime);
            final boolean isLast = isLastPrescribedComplexDoseElement(timedDoseElements, nextTaskTime);
            if (nextTaskTime.isAfter(taskCreationInterval.getEnd()) && isFirst) {
                break;
            }

            if (isFirst && !preview) {
                groupUUId = administrationUtils
                        .generateGroupUUId(Opt.of(therapy.getStart()).orElseGet(DateTime::now));
            }

            Preconditions.checkArgument(preview || groupUUId != null,
                    "groupUUId must be set for start administration!");

            taskRequests.add(createMedicationTaskRequestWithGroupUUId(patientId, groupUUId, therapy,
                    isFirst ? AdministrationTypeEnum.START : AdministrationTypeEnum.ADJUST_INFUSION,
                    nextTaskTime, next.getSecond()));

            if (isLast) {
                final DateTime stopTaskTime = nextTaskTime
                        .plusMinutes(getDoseDurationForDate(durations, nextTaskTime));
                final boolean stopTimeAfterTherapyEnd = isAfterTherapyEnd(therapy, stopTaskTime);
                taskRequests.add(createMedicationTaskRequestWithGroupUUId(patientId, groupUUId, therapy,
                        AdministrationTypeEnum.STOP, stopTimeAfterTherapyEnd ? therapy.getEnd() : stopTaskTime,
                        null));

                if (stopTimeAfterTherapyEnd) {
                    break;
                }
            }

            next = getNextAdministrationTimeWithDose(action, therapy, next.getFirst(), timesWithDosesMap,
                    false);
            nextTaskTime = next.getFirst();

            if (!isLast && isAfterTherapyEnd(therapy, nextTaskTime)) {
                taskRequests.add(createMedicationTaskRequestWithGroupUUId(patientId, groupUUId, therapy,
                        AdministrationTypeEnum.STOP, therapy.getEnd(), null));
            }
        }
    }

    return taskRequests;
}

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

License:Open Source License

@Override
public List<NewTaskRequestDto> createRequestsForAdditionalRateAdministration(final String patientId,
        @Nonnull final TherapyDto therapy, @Nonnull final DateTime timestamp,
        @Nonnull final TherapyDoseDto dose, final String groupUUId, final boolean createStart) {
    Preconditions.checkNotNull(therapy, "therapy");
    Preconditions.checkNotNull(timestamp, "timestamp");
    Preconditions.checkNotNull(dose, "dose");

    final int duration = administrationUtils.calculateDurationForRateQuantityDose(dose);
    dose.setTherapyDoseTypeEnum(TherapyDoseTypeEnum.RATE);

    final String uuId = Opt.of(groupUUId)
            .orElseGet(() -> administrationUtils.generateGroupUUId(DateTime.now()));

    final List<NewTaskRequestDto> requests = new ArrayList<>();
    if (createStart) {
        requests.add(createMedicationTaskRequestWithGroupUUId(patientId, uuId, therapy,
                AdministrationTypeEnum.START, timestamp, dose));
    }// ww  w .  j  av  a2 s  .  com
    requests.add(createMedicationTaskRequestWithGroupUUId(patientId, uuId, therapy, AdministrationTypeEnum.STOP,
            timestamp.plusMinutes(duration), null));

    return requests;
}

From source file:com.marand.thinkmed.medications.service.impl.MedicationsServiceImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)/*w w  w .  ja va2s .  co  m*/
@ServiceMethod(auditing = @Auditing(level = Level.FULL))
@EhrSessioned
public List<AdministrationPatientTaskDto> getAdministrationTasks(final Opt<Collection<String>> careProviderIds,
        final Opt<Collection<String>> patientIds, @Nonnull final Locale locale) {
    Preconditions.checkNotNull(locale, "locale is required");

    final Map<String, PatientDisplayWithLocationDto> patientIdAndPatientWithLocationMap = getPatientDisplayWithLocationDtoMap(
            careProviderIds, patientIds);

    final AdministrationPatientTaskLimitsDto administrationLimits = MedicationPreferencesUtil
            .getAdministrationPatientTaskLimitsPreference();

    final DateTime when = RequestContextHolder.getContext().getRequestTimestamp();

    final Interval searchInterval = new Interval(when.minusMinutes(administrationLimits.getDueTaskOffset()),
            when.plusMinutes(administrationLimits.getFutureTaskOffset()));

    return medicationsTasksProvider.findAdministrationTasks(patientIdAndPatientWithLocationMap, searchInterval,
            administrationLimits.getMaxNumberOfTasks(), locale, when);
}

From source file:com.netflix.ice.login.saml.Saml.java

License:Apache License

/**
 * Process an assertion and setup our session attributes
 *//*from   ww  w  . ja  v a 2s .  co m*/
private void processAssertion(IceSession iceSession, Assertion assertion, LoginResponse lr)
        throws LoginMethodException {
    boolean foundAnAccount = false;
    iceSession.voidSession();
    for (AttributeStatement as : assertion.getAttributeStatements()) {
        // iterate once to assure we set the username first
        for (Attribute attr : as.getAttributes()) {
            if (attr.getName().equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")) {
                for (XMLObject groupXMLObj : attr.getAttributeValues()) {
                    String username = groupXMLObj.getDOM().getTextContent();
                    iceSession.setUsername(username);
                }
            }
        }
        // iterate again for everything else
        for (Attribute attr : as.getAttributes()) {
            if (attr.getName().equals("com.netflix.ice.account")) {
                for (XMLObject groupXMLObj : attr.getAttributeValues()) {
                    String allowedAccount = groupXMLObj.getDOM().getTextContent();
                    if (allowedAccount.equals(config.allAccounts)) {
                        whitelistAllAccounts(iceSession);
                        foundAnAccount = true;
                        logger.info("Found Allow All Accounts: " + allowedAccount);
                        break;
                    } else {
                        if (whitelistAccount(iceSession, allowedAccount)) {
                            foundAnAccount = true;
                            logger.info("Found Account: " + allowedAccount);
                        }
                    }
                }
            }
        }
    }

    //require at least one account
    if (!foundAnAccount) {
        throw new LoginMethodException(
                "SAML Assertion must give at least one Account as part of the Assertion");
    }

    //set expiration date
    DateTime startDate = assertion.getConditions().getNotBefore();
    DateTime endDate = assertion.getConditions().getNotOnOrAfter();
    if (startDate == null || endDate == null) {
        throw new LoginMethodException("Assertion must state an expiration date");
    }
    // Clocks may not be synchronized.
    startDate = startDate.minusMinutes(2);
    endDate = endDate.plusMinutes(2);
    logger.info(startDate.toCalendar(null).getTime().toString());
    logger.info(endDate.toCalendar(null).getTime().toString());
    lr.loginStart = startDate.toCalendar(null).getTime();
    lr.loginEnd = endDate.toCalendar(null).getTime();
}

From source file:com.nike.cerberus.service.CloudFormationService.java

License:Apache License

/**
 * Blocking call that waits for a stack change to complete.  Times out if waiting more than 30 minutes.
 *
 * @param endStatuses Status to end on/*from   ww  w .ja  v  a 2s  .  co m*/
 * @return The final status
 */
public StackStatus waitForStatus(final String stackId, final HashSet<StackStatus> endStatuses) {
    DateTime now = DateTime.now(DateTimeZone.UTC).minusSeconds(10);
    DateTime timeoutDateTime = now.plusMinutes(90);
    Set<String> recordedStackEvents = Sets.newHashSet();
    boolean isRunning = true;
    StackStatus stackStatus = null;

    while (isRunning) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            logger.warn("Thread sleep interrupted. Continuing...", e);
        }
        stackStatus = getStackStatus(stackId);

        if (endStatuses.contains(stackStatus) || stackStatus == null) {
            isRunning = false;
        }

        if (stackStatus != null) {
            List<StackEvent> stackEvents = getStackEvents(stackId);
            stackEvents.sort((o1, o2) -> o1.getTimestamp().compareTo(o2.getTimestamp()));

            for (StackEvent stackEvent : stackEvents) {
                DateTime eventTime = new DateTime(stackEvent.getTimestamp());
                if (!recordedStackEvents.contains(stackEvent.getEventId()) && now.isBefore(eventTime)) {
                    logger.info(String.format("TS: %s, Status: %s, Type: %s, Reason: %s",
                            Chalk.on(stackEvent.getTimestamp().toString()).yellow(),
                            getStatusColor(stackEvent.getResourceStatus()),
                            Chalk.on(stackEvent.getResourceType()).yellow(),
                            Chalk.on(stackEvent.getResourceStatusReason()).yellow()));

                    recordedStackEvents.add(stackEvent.getEventId());
                }
            }
        }

        if (timeoutDateTime.isBeforeNow()) {
            logger.error("Timed out waiting for CloudFormation completion status.");
            isRunning = false;
        }
    }

    return stackStatus;
}

From source file:com.peertopark.java.dates.Dates.java

License:Apache License

public static DateTime addMinutes(DateTime date, int minutes) {
    if (Objects.nonNull(date)) {
        return date.plusMinutes(minutes);
    } else {// w ww.j a v a  2s .  co m
        return null;
    }
}

From source file:com.picdrop.security.token.AbstractClaimSetFactory.java

@Override
public JWTClaimsSet.Builder builder() {
    DateTime now = DateTime.now(DateTimeZone.UTC);
    return new JWTClaimsSet.Builder().audience(configJwtAudience).issueTime(now.toDate())
            .expirationTime(now.plusMinutes(configJwtExpiry).toDate()).issuer(configJwtIssuer);
}

From source file:com.pinterest.teletraan.worker.AutoPromoter.java

License:Apache License

public <E> E getScheduledCheckResult(EnvironBean currEnvBean, PromoteBean promoteBean, List<E> candidates,
        Function<E, Long> timeSupplier) throws Exception {

    E ret = null;// www  .j av a2 s  . co m

    //If we have a cron schedule set, foreach candidates, we compute the earilest due
    // time per schedule for the build.
    CronExpression cronExpression = new CronExpression(promoteBean.getSchedule());
    for (E bean : candidates) {
        DateTime checkTime = new DateTime(timeSupplier.apply(bean));
        if (promoteBean.getDelay() > 0) {
            checkTime.plusMinutes(promoteBean.getDelay());
        }
        DateTime autoDeployDueDate = new DateTime(cronExpression.getNextValidTimeAfter(checkTime.toDate()));
        LOG.info("Auto deploy due time is {} for check time {} for Environment {}",
                autoDeployDueDate.toString(ISODateTimeFormat.dateTime()), checkTime.toString(),
                currEnvBean.getEnv_name());

        if (!autoDeployDueDate.isAfterNow()) {
            ret = bean;
            break;
        }
    }
    return ret;
}

From source file:com.quinsoft.zeidon.domains.DateTimeDomain.java

License:Open Source License

private Object addWithContext(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        Object currentValue, Object operand, String contextName) {
    assert !StringUtils.isBlank(contextName);

    if (operand instanceof AttributeInstance)
        operand = ((AttributeInstance) operand).getValue();

    if (!(operand instanceof Integer) && !(operand instanceof Long)) {
        throw new ZeidonException(
                "When adding to DateTime with a context, operand must be integer or long value.  "
                        + "Type of operand = %s",
                operand.getClass().getName()).prependAttributeDef(attributeDef);
    }/* w  w w.j  a  va 2  s  . c om*/

    int value = ((Number) operand).intValue();
    DateTime dt = (DateTime) currentValue;

    switch (contextName.toLowerCase()) {
    case "day":
    case "days":
        return dt.plusDays(value);

    case "hour":
    case "hours":
        return dt.plusHours(value);

    case "minute":
    case "minutes":
        return dt.plusMinutes(value);

    case "milli":
    case "millis":
    case "millisecond":
    case "milliseconds":
        return dt.plus(((Number) operand).longValue());

    case "month":
    case "months":
        return dt.plusMonths(value);

    case "second":
    case "seconds":
        return dt.plusSeconds(value);

    case "week":
    case "weeks":
        return dt.plusWeeks(value);

    case "year":
    case "years":
        return dt.plusYears(value);
    }

    // TODO Auto-generated method stub
    throw new ZeidonException("Unknown context name '%s' for DateTime domain", contextName)
            .prependAttributeDef(attributeDef);
}

From source file:com.softtek.mdm.security.MyUserDetailServiceImpl.java

@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

    /**/*from   w w w.j  ava 2  s  . c  o  m*/
     * ??????
     * ?id
     * ??id""
     * ?  id
     */
    int lastIndex = name.lastIndexOf(MyUsernamePasswordAuthenticationFilter.USERNAME_ORGID_SPLIT);
    String org_id = name.substring(lastIndex + 1);
    name = name.substring(0, lastIndex);

    List<GrantedAuthority> auths = null;
    String mString = "";

    if (StringUtil.isBlank(org_id)) {
        //????/?
        ManagerModel manager = managerService.findOneInstitution(name);

        if (manager != null) {
            //============license   start=============
            List<OrgManagerRelationModel> list = orgManagerRelationService
                    .findRecordsByManagerId(manager.getId());
            if ((!CollectionUtils.isEmpty(list))
                    && manager.getUser_type() != Integer.parseInt(AuthStatus.SOFTTEK_AMDIN.toString())) {
                @SuppressWarnings("unchecked")
                List<Integer> ids = (List<Integer>) CollectionUtils.collect(list, new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        if (input instanceof OrgManagerRelationModel) {
                            OrgManagerRelationModel org = (OrgManagerRelationModel) input;
                            return org.getOrganization() != null ? org.getOrganization().getId() : null;
                        }
                        return null;
                    }
                });

                checkLicense(ids);
            }
            //============license   end=============

            if (manager.getLogin_count() > (Integer) 2) {
                DateTime dTime = new DateTime(manager.getUpdateTime());
                if (dTime.plusMinutes(5).isAfterNow()) {
                    mString = messageSource.getMessage(
                            "security.myuserdetailserviceimpl.loaduserbyusername.lockonfive", null,
                            LocaleContextHolder.getLocale());
                    throw new UsernameNotFoundException(mString);
                }
            }

            //????
            if ("0".equals(manager.getStatus())) {
                mString = messageSource.getMessage(
                        "security.myuserdetailserviceimpl.loaduserbyusername.account.disabled", null,
                        LocaleContextHolder.getLocale());
                throw new UsernameNotFoundException(mString);
            }

            if (manager.getUser_type() == (Integer) 2) {
                //?
                List<OrganizationModel> orgList = organizationService
                        .findEnableOrganizationRecordsByManagerId(manager.getId());
                if (CollectionUtils.isEmpty(orgList)) {
                    mString = messageSource.getMessage(
                            "security.myuserdetailserviceimpl.loaduserbyusername.organization.nomanage", null,
                            LocaleContextHolder.getLocale());
                    throw new UsernameNotFoundException(mString);
                }
            }

            //?????
            //?????
            auths = obtainAuths(manager.getUser_type());

            ManagerModel temp = new ManagerModel();
            temp.setId(manager.getId());
            temp.setLogin_count((manager.getLogin_count() == null ? 0 : manager.getLogin_count()) + 1);
            managerService.update(temp);
            if (temp.getLogin_count() > (Integer) 1) {
                //??
                SecurityEventLogModel securityEventLog = new SecurityEventLogModel();
                Object[] obj = { manager.getUsername() };
                String operateContent = messageSource.getMessage("logs.system.manager.error.password", obj,
                        LocaleContextHolder.getLocale());
                securityEventLog.setEventType("4");
                securityEventLog.setLevel("1");
                securityEventLog.setOperateContent(operateContent);
                securityEventLog.setCreateBy(manager.getId());
                securityEventLog.setUpdateBy(manager.getId());
                securityEventLogService.insertSecurityEventLog(securityEventLog);
            }

            return new User(manager.getUsername(), manager.getPassword(), true, true, true, true, auths);

        } else {
            ///??
            manager = managerService.findOneByName(name);
            if (manager != null) {
                Object[] objects = { name };
                mString = messageSource.getMessage(
                        "security.myuserdetailserviceimpl.loaduserbyusername.sigin.error.enter", objects,
                        LocaleContextHolder.getLocale());
                throw new UsernameNotFoundException(mString);
            }
            Object[] objs = { name };
            String UsernameNotFound = messageSource.getMessage(
                    "security.myuserdetailserviceimpl.loaduserbyusername.account.notexists", objs,
                    LocaleContextHolder.getLocale());
            throw new UsernameNotFoundException(UsernameNotFound);
        }
    } else {
        List<Integer> ids = new ArrayList<>();
        ids.add(Integer.valueOf(org_id));
        checkLicense(ids);

        ///??
        //??
        ManagerModel manager = managerService.findOneByOrgAndName(Integer.valueOf(org_id), name);
        if (manager != null) {
            if (manager.getUser() != null) {
                //??????
                auths = obtainAuths(manager.getUser_type());

                ManagerModel temp = new ManagerModel();
                temp.setId(manager.getId());
                temp.setLogin_count((manager.getLogin_count() == null ? 0 : manager.getLogin_count()) + 1);
                managerService.update(temp);

                UserModel user = userService.findOne(manager.getUser().getId());
                if (user != null) {
                    if (user.getIs_active() == (Integer) 0) {
                        Object[] objects = { name };
                        mString = messageSource.getMessage(
                                "security.myuserdetailserviceimpl.loaduserbyusername.account.unavtive", objects,
                                LocaleContextHolder.getLocale());
                        throw new UsernameNotFoundException(mString);
                    }
                    if (user.getIs_lock() == (Integer) 1) {
                        Object[] objects = { name };
                        mString = messageSource.getMessage(
                                "security.myuserdetailserviceimpl.loaduserbyusername.account.lock", objects,
                                LocaleContextHolder.getLocale());
                        throw new UsernameNotFoundException(mString);
                    }
                }
                return new User(manager.getUsername(), manager.getPassword(), true, true, true, true, auths);

            } else {
                if (manager.getLogin_count() >= (Integer) 3) {
                    DateTime dTime = new DateTime(manager.getUpdateTime());
                    if (dTime.plusMinutes(5).isAfterNow()) {
                        mString = messageSource.getMessage(
                                "security.myuserdetailserviceimpl.loaduserbyusername.lockonfive", null,
                                LocaleContextHolder.getLocale());
                        throw new UsernameNotFoundException(mString);
                    }
                }
                Object[] obts = { name };
                mString = messageSource.getMessage(
                        "security.myuserdetailserviceimpl.loaduserbyusername.sign.error.login", obts,
                        LocaleContextHolder.getLocale());
                throw new UsernameNotFoundException(mString);
            }

        }
        //???
        UserModel user = userService.findUser(name, Integer.parseInt(org_id));
        if (user != null) {
            if (user.getLogin_count() > (Integer) 2) {
                DateTime dTime = new DateTime(user.getUpdateTime());
                if (dTime.plusMinutes(5).isAfterNow()) {
                    mString = messageSource.getMessage(
                            "security.myuserdetailserviceimpl.loaduserbyusername.lockonfive", null,
                            LocaleContextHolder.getLocale());
                    throw new UsernameNotFoundException(mString);
                }
            }
            if (user.getIs_active() == (Integer) 0) {
                Object[] objects = { name };
                mString = messageSource.getMessage(
                        "security.myuserdetailserviceimpl.loaduserbyusername.account.unavtive", objects,
                        LocaleContextHolder.getLocale());
                throw new UsernameNotFoundException(mString);
            }
            if (user.getIs_lock() == (Integer) 1) {
                Object[] objects = { name };
                mString = messageSource.getMessage(
                        "security.myuserdetailserviceimpl.loaduserbyusername.account.lock", objects,
                        LocaleContextHolder.getLocale());
                throw new UsernameNotFoundException(mString);
            }
            //?????
            auths = obtainAuths(user.getType());

            UserModel temp = new UserModel();
            temp.setId(user.getId());
            temp.setLogin_count((user.getLogin_count() == null ? 0 : user.getLogin_count()) + 1);
            userService.update(temp);

            return new User(user.getUsername(), user.getPassword(), true, true, true, true, auths);
        } else {

            //???
            //??
            Object[] objs = { name };
            String UsernameNotFound = messageSource.getMessage(
                    "security.myuserdetailserviceimpl.loaduserbyusername.account.notexists", objs,
                    LocaleContextHolder.getLocale());
            throw new UsernameNotFoundException(UsernameNotFound);
        }
    }
}