Example usage for org.apache.commons.lang.time DateUtils addSeconds

List of usage examples for org.apache.commons.lang.time DateUtils addSeconds

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils addSeconds.

Prototype

public static Date addSeconds(Date date, int amount) 

Source Link

Document

Adds a number of seconds to a date returning a new object.

Usage

From source file:org.jasig.schedassist.impl.caldav.CaldavCalendarDataDaoImpl.java

@Override
public void checkForConflicts(IScheduleOwner owner, AvailableBlock block) throws ConflictExistsException {
    // use a start and end time slightly smaller than the block to avoid events that start/end on the edge of the block
    Date start = DateUtils.addSeconds(block.getStartTime(), 1);
    Date end = DateUtils.addSeconds(block.getEndTime(), -1);
    List<CalendarWithURI> calendars = getCalendarsInternal(owner.getCalendarAccount(), start, end);
    for (CalendarWithURI calendar : calendars) {
        ComponentList events = calendar.getCalendar().getComponents(VEvent.VEVENT);
        for (Object component : events) {
            VEvent event = (VEvent) component;
            if (this.eventUtils.willEventCauseConflict(owner.getCalendarAccount(), event)) {
                if (log.isDebugEnabled()) {
                    log.debug("conflict detected for " + owner + " at block " + block + ", event: " + event);
                }//from   ww  w  .  ja v  a 2  s  .com
                throw new ConflictExistsException("an appointment already exists for " + block);
            }
        }
    }
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilder.java

/**
 * /*w w w  .  ja va 2  s . c  om*/
 * @param startTimePhrase
 * @param endTimePhrase
 * @param daysOfWeekPhrase
 * @param startDate
 * @param endDate
 * @param visitorLimit
 * @param meetingLocation
 * @return
 * @throws InputFormatException
 */
public static SortedSet<AvailableBlock> createBlocks(final String startTimePhrase, final String endTimePhrase,
        final String daysOfWeekPhrase, final Date startDate, final Date endDate, final int visitorLimit,
        final String meetingLocation) throws InputFormatException {
    SortedSet<AvailableBlock> blocks = new TreeSet<AvailableBlock>();
    // set time of startDate to 00:00:00
    Date realStartDate = DateUtils.truncate(startDate, Calendar.DATE);
    // set time of endDate to 23:59:59
    Date dayAfterEndDate = DateUtils.truncate(DateUtils.addDays(endDate, 1), Calendar.DATE);
    Date realEndDate = DateUtils.addSeconds(dayAfterEndDate, -1);

    if (LOG.isDebugEnabled()) {
        LOG.debug("createBlocks calculated realStartDate: " + realStartDate + ", realEndDate: " + realEndDate);
    }

    List<Date> matchingDays = matchingDays(daysOfWeekPhrase, realStartDate, realEndDate);
    for (Date matchingDate : matchingDays) {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(matchingDate);
        Calendar endCalendar = (Calendar) startCalendar.clone();

        interpretAndUpdateTime(startTimePhrase, startCalendar);
        interpretAndUpdateTime(endTimePhrase, endCalendar);

        Date blockStartTime = startCalendar.getTime();
        Date blockEndTime = endCalendar.getTime();
        if (!blockEndTime.after(blockStartTime)) {
            throw new InputFormatException("Start time must occur before end time");
        }
        if (CommonDateOperations.equalsOrAfter(blockStartTime, realStartDate)
                && CommonDateOperations.equalsOrBefore(blockEndTime, realEndDate)) {
            AvailableBlock block = new AvailableBlock(blockStartTime, blockEndTime, visitorLimit,
                    meetingLocation);
            blocks.add(block);
        }

    }
    return blocks;
}

From source file:org.jasig.schedassist.model.VisibleSchedule.java

/**
 * Returns the set of {@link AvailableBlock} objects within this instance
 * that conflict with the argument.//from ww  w . j a  v  a  2 s  .  co  m
 * 
 * A conflict is defined as any overlap of 1 minute or more.
 * 
 * @param conflict
 * @return a set of conflicting blocks within this instance that conflict with the block argument
 */
protected Set<AvailableBlock> locateConflicting(final AvailableBlock conflict) {
    Set<AvailableBlock> conflictingKeys = new HashSet<AvailableBlock>();

    Date conflictDayStart = DateUtils.truncate(conflict.getStartTime(), java.util.Calendar.DATE);
    Date conflictDayEnd = DateUtils.addDays(DateUtils.truncate(conflict.getEndTime(), java.util.Calendar.DATE),
            1);
    conflictDayEnd = DateUtils.addMinutes(conflictDayEnd, -1);

    AvailableBlock rangeStart = AvailableBlockBuilder.createPreferredMinimumDurationBlock(conflictDayStart,
            meetingDurations);
    LOG.debug("rangeStart: " + rangeStart);
    AvailableBlock rangeEnd = AvailableBlockBuilder.createBlockEndsAt(conflictDayEnd,
            meetingDurations.getMinLength());
    LOG.debug("rangeEnd: " + rangeStart);

    SortedMap<AvailableBlock, AvailableStatus> subMap = blockMap.subMap(rangeStart, rangeEnd);
    LOG.debug("subset of blockMap size: " + subMap.size());

    for (AvailableBlock mapKey : subMap.keySet()) {
        // all the AvailableBlock keys in the map have start/endtimes truncated to the minute
        // shift the key slightly forward (10 seconds) so that conflicts that start or end on the
        // same minute as a key does don't result in false positives
        Date minuteWithinBlock = DateUtils.addSeconds(mapKey.getStartTime(), 10);
        boolean shortCircuit = true;
        while (shortCircuit && CommonDateOperations.equalsOrBefore(minuteWithinBlock, mapKey.getEndTime())) {
            if (minuteWithinBlock.before(conflict.getEndTime())
                    && minuteWithinBlock.after(conflict.getStartTime())) {
                conflictingKeys.add(mapKey);
                shortCircuit = false;
            }
            minuteWithinBlock = DateUtils.addMinutes(minuteWithinBlock, 1);
        }
    }

    return conflictingKeys;
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

private void calculateCosts(Organization org) {
    Currency cur = FinancialUtils.getLegalEntityCurrency(org);
    String curId = cur.getId();/*from  w w w. jav a2  s.c o  m*/
    Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider(org.getClient().getId())
            .getChildTree(org.getId(), true);
    String orgId = org.getId();

    int costPrecision = cur.getCostingPrecision().intValue();
    int stdPrecision = cur.getStandardPrecision().intValue();
    CostingRuleProcess crp = new CostingRuleProcess();
    // Update cost of inventories and process starting physical inventories.
    ScrollableResults icls = getCloseInventoryLines(orgs);
    String productId = "";
    BigDecimal totalCost = BigDecimal.ZERO;
    BigDecimal totalStock = BigDecimal.ZERO;
    int i = 0;
    try {
        while (icls.next()) {
            InventoryCountLine icl = (InventoryCountLine) icls.get(0);
            if (!productId.equals(icl.getProduct().getId())) {
                productId = icl.getProduct().getId();
                HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
                totalCost = stock.get("cost");
                totalStock = stock.get("stock");
            }

            MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
            trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
            trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));

            BigDecimal trxCost = BigDecimal.ZERO;
            if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
                trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock, stdPrecision,
                        BigDecimal.ROUND_HALF_UP);
            }
            if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
                // Last transaction adjusts remaining cost amount.
                trxCost = totalCost;
            }
            trx.setTransactionCost(trxCost);
            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            OBDal.getInstance().save(trx);
            Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            BigDecimal cost = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(trx.getMovementQuantity()) != 0) {
                cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision, BigDecimal.ROUND_HALF_UP);
            }
            if (!legalEntityCur.equals(cur)) {
                cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
                        icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
            }

            InventoryCountLine initICL = icl.getRelatedInventory();
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);

            totalCost = totalCost.subtract(trxCost);
            // MovementQty is already negative so add to totalStock to decrease it.
            totalStock = totalStock.add(trx.getMovementQuantity());

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                cur = OBDal.getInstance().get(Currency.class, curId);
            }
            i++;
        }
    } finally {
        icls.close();
    }

    OBDal.getInstance().flush();
    insertTrxCosts();

}

From source file:org.openbravo.costing.CostingRuleProcess.java

private void updateInventoriesCostAndProcessInitInventories(String ruleId, Date startingDate,
        boolean existsPreviousRule) {
    CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId);
    for (CostingRuleInit cri : rule.getCostingRuleInitList()) {
        for (InventoryCountLine icl : cri.getCloseInventory().getMaterialMgmtInventoryCountLineList()) {
            MaterialTransaction trx = getInventoryLineTransaction(icl);
            // Remove 1 second from transaction date to ensure that cost is calculated with previous
            // costing rule.
            trx.setTransactionProcessDate(DateUtils.addSeconds(startingDate, -1));
            BigDecimal trxCost = BigDecimal.ZERO;
            BigDecimal cost = null;
            Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            if (existsPreviousRule) {
                trxCost = CostingUtils.getTransactionCost(trx, startingDate, true, cur);
                if (trx.getMovementQuantity().compareTo(BigDecimal.ZERO) != 0) {
                    cost = trxCost.divide(trx.getMovementQuantity().abs(), cur.getCostingPrecision().intValue(),
                            RoundingMode.HALF_UP);
                }//w w w . j  av  a2  s .  c o  m
            } else {
                // Insert transaction cost record big ZERO cost.
                cur = trx.getClient().getCurrency();
                TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
                transactionCost.setInventoryTransaction(trx);
                transactionCost.setCostDate(trx.getTransactionProcessDate());
                transactionCost.setClient(trx.getClient());
                transactionCost.setOrganization(trx.getOrganization());
                transactionCost.setCost(BigDecimal.ZERO);
                transactionCost.setCurrency(trx.getClient().getCurrency());
                transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null
                        ? trx.getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()
                        : trx.getMovementDate());
                List<TransactionCost> trxCosts = trx.getTransactionCostList();
                trxCosts.add(transactionCost);
                trx.setTransactionCostList(trxCosts);
                OBDal.getInstance().save(trx);
            }

            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            trx.setCurrency(cur);
            trx.setTransactionCost(trxCost);
            OBDal.getInstance().save(trx);
            InventoryCountLine initICL = getInitIcl(cri.getInitInventory(), icl);
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);
        }
        OBDal.getInstance().flush();
        new InventoryCountProcess().processInventory(cri.getInitInventory(), false);
    }
    if (!existsPreviousRule) {
        updateInitInventoriesTrxDate(startingDate, ruleId);
    }
}

From source file:org.openmrs.api.impl.OrderServiceImpl.java

/**
 * To support MySQL datetime values (which are only precise to the second) we subtract one
 * second. Eventually we may move this method and enhance it to subtract the smallest moment the
 * underlying database will represent.//  ww w.  j a v  a 2  s .c  om
 * 
 * @param date
 * @return one moment before date
 */
private Date aMomentBefore(Date date) {
    return DateUtils.addSeconds(date, -1);
}

From source file:org.openmrs.module.casereport.CaseReportUtil.java

/**
 * Runs the SQL cohort query with the specified name and creates a case report for each matched
 * patient of none exists/*  w ww.  j  a v  a 2 s .  c o  m*/
 *
 * @param taskDefinition the scheduler taskDefinition inside which the trigger is being run
 * @throws APIException
 * @throws EvaluationException
 * @should fail if no sql cohort query matches the specified trigger name
 * @should create case reports for the matched patients
 * @should set the last execution time in the evaluation context
 * @should add a new trigger to an existing queue item for the patient
 * @should not create a duplicate trigger for the same patient
 * @should set the concept mappings in the evaluation context
 * @should fail for a task where the last execution time cannot be resolved
 */
public synchronized static void executeTask(TaskDefinition taskDefinition)
        throws APIException, EvaluationException {
    if (taskDefinition == null) {
        throw new APIException("TaskDefinition can't be null");
    }

    String triggerName = taskDefinition.getProperty(CaseReportConstants.TRIGGER_NAME_TASK_PROPERTY);
    if (StringUtils.isBlank(triggerName)) {
        throw new APIException(taskDefinition.getName() + " task doesn't have a "
                + CaseReportConstants.TRIGGER_NAME_TASK_PROPERTY + " property");
    }
    SqlCohortDefinition definition = getSqlCohortDefinition(triggerName);
    if (definition == null) {
        throw new APIException("No sql cohort query was found that matches the name: " + triggerName);
    }
    EvaluationContext evaluationContext = new EvaluationContext();
    Map<String, Object> params = new HashMap<>();
    if (definition.getParameter(CaseReportConstants.LAST_EXECUTION_TIME) != null) {
        Date lastExecutionTime = taskDefinition.getLastExecutionTime();
        if (lastExecutionTime == null && taskDefinition.getRepeatInterval() != null
                && taskDefinition.getRepeatInterval() > 0) {
            //TODO add a unit test for this
            //default to now minus repeat interval
            lastExecutionTime = DateUtils.addSeconds(new Date(),
                    -taskDefinition.getRepeatInterval().intValue());
        }
        if (lastExecutionTime == null) {
            throw new APIException("Failed to resolve the value for the last execution time");
        }
        params.put(CaseReportConstants.LAST_EXECUTION_TIME, lastExecutionTime);
    }

    if (definition.getParameters() != null) {
        for (Parameter p : definition.getParameters()) {
            if (p.getName().startsWith(CaseReportConstants.CIEL_MAPPING_PREFIX)) {
                Concept concept = CaseReportUtil.getConceptByMappingString(p.getName(), true);
                params.put(p.getName(), concept.getConceptId());
            }
        }
    }

    evaluationContext.setParameterValues(params);
    Cohort cohort = (Cohort) DefinitionContext.evaluate(definition, evaluationContext);

    PatientService ps = Context.getPatientService();
    CaseReportService caseReportService = Context.getService(CaseReportService.class);
    List<CaseReport> autoSubmitReports = new ArrayList<>(cohort.getMemberIds().size());
    for (Integer patientId : cohort.getMemberIds()) {
        Patient patient = ps.getPatient(patientId);
        if (patient == null) {
            throw new APIException("No patient found with patientId: " + patientId);
        }

        boolean autoSubmit = false;
        if ("true".equals(taskDefinition.getProperty(CaseReportConstants.AUTO_SUBMIT_TASK_PROPERTY))) {
            autoSubmit = true;
        }
        CaseReport caseReport = createReportIfNecessary(patient, autoSubmit, triggerName);
        if (caseReport != null) {
            //We can't auto submit an existing report because the surveillance officer needs
            //to take a look at the other triggers to be included in the existing report
            if (caseReport.getId() == null && autoSubmit) {
                caseReport.setAutoSubmitted(true);
                autoSubmitReports.add(caseReport);
            }
            caseReportService.saveCaseReport(caseReport);
        } else {
            log.debug(patient + " already has an item in the queue with the trigger " + triggerName);
        }
    }

    for (CaseReport caseReport : autoSubmitReports) {
        //TODO reports should be auto submitted in parallel
        try {
            CaseReportForm form = new CaseReportForm(caseReport);
            caseReport.setReportForm(new ObjectMapper().writeValueAsString(form));
            caseReportService.submitCaseReport(caseReport);
        } catch (Throwable t) {
            log.warn("Failed to auto submit " + caseReport, t);
        }
    }
}

From source file:org.openmrs.module.reporting.evaluation.EvaluationUtil.java

/**
 * This method will parse the passed expression and return a value based on the following
 * criteria:<br/>/*from w ww .j av a2  s . c om*/
 * <ul>
 * <li>Any string that matches a passed parameter will be replaced by the value of that parameter
 * <li>If this date is followed by an expression, it will attempt to evaluate this by
 * incrementing/decrementing days/weeks/months/years as specified</li>
 * <li>Examples: Given 2 parameters:
 * <ul>
 * <li>report.startDate = java.util.Date with value of [2007-01-10]
 * <li>report.gender = "male"
 * </ul>
 * The following should result:<br/>
 * <br/>
 * <pre>
 * evaluateParameterExpression("report.startDate") -> "2007-01-10" as Date
 * <pre>
 * </ul>
 * 
 * @param expression
 * @return value for given expression, as an <code>Object</code>
 * @throws org.openmrs.module.reporting.evaluation.parameter.ParameterException
 */
public static Object evaluateParameterExpression(String expression, Map<String, Object> parameters)
        throws ParameterException {

    log.debug("evaluateParameterExpression(): " + expression);

    log.debug("Starting expression: " + expression);
    String[] paramAndFormat = expression.split(FORMAT_SEPARATOR, 2);
    Object paramValueToFormat = null;

    try {
        Matcher matcher = expressionPattern.matcher(paramAndFormat[0]);
        if (matcher.matches()) {
            String parameterName = matcher.group(1);
            paramValueToFormat = parameters.get(parameterName);
            if (paramValueToFormat == null) {
                log.debug("Looked like an expression but the parameter value is null");
            } else {
                String operations = matcher.group(2);
                Matcher opMatcher = operationPattern.matcher(operations);
                while (opMatcher.find()) {
                    String op = opMatcher.group(1);
                    String number = opMatcher.group(2);
                    String unit = opMatcher.group(3).toLowerCase();
                    if (paramValueToFormat instanceof Date) {
                        if (!op.matches("[+-]")) {
                            throw new IllegalArgumentException("Dates only support the + and - operators");
                        }
                        Integer numAsInt;
                        try {
                            numAsInt = Integer.parseInt(number);
                        } catch (NumberFormatException ex) {
                            throw new IllegalArgumentException(
                                    "Dates do not support arithmetic with floating-point values");
                        }

                        if ("-".equals(op)) {
                            numAsInt = -numAsInt;
                        }
                        if ("w".equals(unit)) {
                            unit = "d";
                            numAsInt *= 7;
                        }
                        if ("ms".equals(unit)) {
                            paramValueToFormat = DateUtils.addMilliseconds((Date) paramValueToFormat, numAsInt);
                        } else if ("s".equals(unit)) {
                            paramValueToFormat = DateUtils.addSeconds((Date) paramValueToFormat, numAsInt);
                        } else if ("h".equals(unit)) {
                            paramValueToFormat = DateUtils.addHours((Date) paramValueToFormat, numAsInt);
                        } else if ("m".equals(unit)) {
                            paramValueToFormat = DateUtils.addMonths((Date) paramValueToFormat, numAsInt);
                        } else if ("y".equals(unit)) {
                            paramValueToFormat = DateUtils.addYears((Date) paramValueToFormat, numAsInt);
                        } else if ("".equals(unit) || "d".equals(unit)) {
                            paramValueToFormat = DateUtils.addDays((Date) paramValueToFormat, numAsInt);
                        } else {
                            throw new IllegalArgumentException("Unknown unit: " + unit);
                        }
                    } else { // assume it's a number
                        if (!"".equals(unit)) {
                            throw new IllegalArgumentException("Can't specify units in a non-date expression");
                        }
                        if (paramValueToFormat instanceof Integer && number.matches("\\d+")) {
                            Integer parsed = Integer.parseInt(number);
                            if ("+".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) + parsed;
                            } else if ("-".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) - parsed;
                            } else if ("*".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) * parsed;
                            } else if ("/".equals(op)) {
                                paramValueToFormat = ((Integer) paramValueToFormat) / parsed;
                            } else {
                                throw new IllegalArgumentException("Unknown operator " + op);
                            }
                        } else {
                            // since one or both are decimal values, do double arithmetic
                            Double parsed = Double.parseDouble(number);
                            if ("+".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() + parsed;
                            } else if ("-".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() - parsed;
                            } else if ("*".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() * parsed;
                            } else if ("/".equals(op)) {
                                paramValueToFormat = ((Number) paramValueToFormat).doubleValue() / parsed;
                            } else {
                                throw new IllegalArgumentException("Unknown operator " + op);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        log.debug(e.getMessage());
        throw new ParameterException("Error handling expression: " + paramAndFormat[0], e);
    }

    paramValueToFormat = ObjectUtil.nvl(paramValueToFormat, parameters.get(paramAndFormat[0]));
    if (ObjectUtil.isNull(paramValueToFormat)) {
        if (parameters.containsKey(paramAndFormat[0])) {
            return paramValueToFormat;
        } else {
            return expression;
        }
    }
    log.debug("Evaluated to: " + paramValueToFormat);

    // Attempt to format the evaluated value if appropriate
    if (paramAndFormat.length == 2) {
        paramValueToFormat = ObjectUtil.format(paramValueToFormat, paramAndFormat[1]);
    }

    return paramValueToFormat;
}

From source file:org.sakaiproject.chat2.model.impl.ChatManagerImpl.java

/**
 * {@inheritDoc}// w  w w . j a va2  s.  c  o m
 */
public boolean getCanPostMessage(ChatChannel channel) {
    // We don't currently support posting messages by anonymous users
    if (SessionManager.getCurrentSessionUserId() == null)
        return false;

    boolean allowed = false;
    if (channel != null) {
        allowed = can(ChatFunctions.CHAT_FUNCTION_NEW, channel.getContext());
        if (allowed) {
            // check the dates if they are set (https://jira.sakaiproject.org/browse/SAK-24207)
            Date today = new Date();
            Date start = channel.getStartDate();
            if (start == null) {
                start = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                start = DateUtils.truncate(start, Calendar.DATE);
            }
            Date end = channel.getEndDate();
            if (end == null) {
                end = today;
            } else {
                // fix up the date to shift to be beginning or end of the day (drop any time component)
                end = DateUtils.truncate(end, Calendar.DATE);
                end = DateUtils.addSeconds(end, 86398); // just short of a full day in seconds
            }
            if (today.before(start) || today.after(end)) {
                // today is outside the configured dates so no posting allowed
                allowed = false;
            }
        }
    }
    return allowed;
}

From source file:org.sakaiproject.chat2.tool.DecoratedChatChannel.java

public void setEndDate(Date endDate) {
    if (endDate != null) {
        // fix up the date to shift to be beginning or end of the day (drop any time component)
        endDate = DateUtils.truncate(endDate, Calendar.DATE);
        endDate = DateUtils.addSeconds(endDate, 86398); // just short of a full day in seconds
    }/*w ww .jav  a2  s.c  o  m*/
    this.endDate = endDate;
}