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

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

Introduction

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

Prototype

public static Date addMilliseconds(Date date, int amount) 

Source Link

Document

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

Usage

From source file:com.chortitzer.web.bas.controller.GranosBean.java

/**
 * @param selectedRango the selectedRango to set
 *///from   w w  w.  j ava2 s .  c om
public void setSelectedRango(int selectedRango) {
    try {
        this.selectedRango = selectedRango;
        if (selectedRango != 0) {
            setFechaHasta(new Date());
            switch (selectedRango) {
            case 1:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH));
                break;
            case 2:
                fechaDesde = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
                setFechaDesde(DateUtils.addDays(fechaDesde, -1));
                fechaHasta = DateUtils.addDays(fechaDesde, 1);
                setFechaHasta(DateUtils.addMilliseconds(fechaHasta, -1));
                break;
            case 3:
                calendar = DateUtils.truncate(calendar, Calendar.DAY_OF_MONTH);
                calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
                setFechaDesde(calendar.getTime());
                break;
            case 4:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.MONTH));
                break;
            case 5:
                setFechaDesde(DateUtils.truncate(new Date(), Calendar.YEAR));
                break;
            }
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage()));
    }
}

From source file:ch.algotrader.service.ForexServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w  w  .j av  a  2 s .c o m*/
 */
@Override
public void hedgeForex() {

    Strategy server = this.strategyDao.findServer();

    CoreConfig coreConfig = this.coreConfig;
    // potentially close a Forex Future position if it is below the MinTimeToExpiration
    if (coreConfig.isFxFutureHedgeEnabled()) {

        // get the closing orders
        final List<Order> orders = new ArrayList<>();
        for (Position position : this.lookupService.getOpenPositionsByStrategyTypeAndUnderlyingType(
                StrategyImpl.SERVER, Future.class, Forex.class)) {

            // check if expiration is below minimum
            Future future = (Future) position.getSecurity();

            Forex forex = (Forex) future.getUnderlying();

            Subscription forexSubscription = this.subscriptionDao.findByStrategyAndSecurity(StrategyImpl.SERVER,
                    forex.getId());
            if (!forexSubscription.hasProperty("hedgingFamily")) {
                throw new IllegalStateException("no hedgingFamily defined for forex " + forex);
            }

            FutureFamily futureFamily = this.futureFamilyDao
                    .load(forexSubscription.getIntProperty("hedgingFamily"));
            if (!future.getSecurityFamily().equals(futureFamily)) {
                // continue if forex is not hedged with this futureFamily
                continue;
            }

            if (future.getTimeToExpiration(this.engineManager.getCurrentEPTime()) < coreConfig
                    .getFxFutureHedgeMinTimeToExpiration()) {

                Order order = this.orderService
                        .createOrderByOrderPreference(coreConfig.getFxHedgeOrderPreference());
                order.setStrategy(server);
                order.setSecurity(future);
                order.setQuantity(Math.abs(position.getQuantity()));
                order.setSide(position.getQuantity() > 0 ? Side.SELL : Side.BUY);

                orders.add(order);
            }
        }

        // setup an TradeCallback so that new hedge positions are only setup when existing positions are closed
        if (orders.size() > 0) {

            if (NOTIFICATION_LOGGER.isInfoEnabled()) {
                NOTIFICATION_LOGGER.info(
                        "{} fx hedging position(s) have been closed due to approaching expiration, please run equalizeForex again",
                        orders.size());
            }
            // send the orders
            for (Order order : orders) {
                this.orderService.sendOrder(order);
            }

            return; // do not go any furter because closing trades will have to finish first
        }
    }

    // process all non-base currency balances
    Collection<BalanceVO> balances = this.portfolioService.getBalances();
    for (BalanceVO balance : balances) {

        Currency portfolioBaseCurrency = this.commonConfig.getPortfolioBaseCurrency();
        if (balance.getCurrency().equals(portfolioBaseCurrency)) {
            continue;
        }

        // get the netLiqValueBase
        double netLiqValue = balance.getNetLiqValue().doubleValue();
        double netLiqValueBase = balance.getExchangeRate() * netLiqValue;

        // check if amount is larger than minimum
        if (Math.abs(netLiqValueBase) >= coreConfig.getFxHedgeMinAmount()) {

            // get the forex
            Forex forex = this.forexDao.getForex(portfolioBaseCurrency, balance.getCurrency());

            double tradeValue = forex.getBaseCurrency().equals(portfolioBaseCurrency) ? netLiqValueBase
                    : netLiqValue;

            // create the order
            Order order = this.orderService
                    .createOrderByOrderPreference(coreConfig.getFxHedgeOrderPreference());
            order.setStrategy(server);

            // if a hedging family is defined for this Forex use it instead of the Forex directly
            int qty;
            if (coreConfig.isFxFutureHedgeEnabled()) {

                Subscription forexSubscription = this.subscriptionDao
                        .findByStrategyAndSecurity(StrategyImpl.SERVER, forex.getId());
                if (!forexSubscription.hasProperty("hedgingFamily")) {
                    throw new IllegalStateException("no hedgingFamily defined for forex " + forex);
                }

                FutureFamily futureFamily = this.futureFamilyDao
                        .load(forexSubscription.getIntProperty("hedgingFamily"));

                Date targetDate = DateUtils.addMilliseconds(this.engineManager.getCurrentEPTime(),
                        coreConfig.getFxFutureHedgeMinTimeToExpiration());
                Future future = this.futureService.getFutureByMinExpiration(futureFamily.getId(), targetDate);

                // make sure the future is subscriped
                this.marketDataService.subscribe(server.getName(), future.getId());

                order.setSecurity(future);

                // round to the number of contracts
                qty = (int) MathUtils.round(tradeValue / futureFamily.getContractSize(), 0);

            } else {

                order.setSecurity(forex);

                // round to batchSize
                qty = (int) RoundUtil.roundToNextN(tradeValue, coreConfig.getFxHedgeBatchSize());
            }

            if (forex.getBaseCurrency().equals(portfolioBaseCurrency)) {

                // expected case
                order.setQuantity(Math.abs(qty));
                order.setSide(qty > 0 ? Side.BUY : Side.SELL);

            } else {

                // reverse case
                order.setQuantity(Math.abs(qty));
                order.setSide(qty > 0 ? Side.SELL : Side.BUY);
            }

            this.orderService.sendOrder(order);

        } else {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("no forex hedge is performed on {} because amount {} is below {}",
                        balance.getCurrency(), RoundUtil.getBigDecimal(Math.abs(netLiqValueBase)),
                        coreConfig.getFxHedgeMinAmount());
            }
            continue;
        }
    }

}

From source file:com.silverpeas.gallery.model.MediaTest.java

@Test
public void isVisible() {
    Media media = defaultMedia();

    media.setVisibilityPeriod(null);/*  ww w  . ja v  a2 s  .c o m*/

    assertThat(media.isVisible(DateUtil.getNow()), is(true));
    assertThat(media.isVisible(beginVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(beginVisibilityDate, -1)), is(true));
    assertThat(media.isVisible(endVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(endVisibilityDate, 1)), is(true));

    media.setVisibilityPeriod(Period.from(beginVisibilityDate, DateUtil.MAXIMUM_DATE));

    assertThat(media.isVisible(DateUtil.getNow()), is(true));
    assertThat(media.isVisible(beginVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(beginVisibilityDate, -1)), is(false));
    assertThat(media.isVisible(endVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(endVisibilityDate, 1)), is(true));

    media.setVisibilityPeriod(Period.from(DateUtil.MINIMUM_DATE, endVisibilityDate));

    assertThat(media.isVisible(DateUtil.getNow()), is(true));
    assertThat(media.isVisible(beginVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(beginVisibilityDate, -1)), is(true));
    assertThat(media.isVisible(endVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(endVisibilityDate, 1)), is(false));

    media.setVisibilityPeriod(Period.from(beginVisibilityDate, endVisibilityDate));

    assertThat(media.isVisible(DateUtil.getNow()), is(true));
    assertThat(media.isVisible(beginVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(beginVisibilityDate, -1)), is(false));
    assertThat(media.isVisible(endVisibilityDate), is(true));
    assertThat(media.isVisible(DateUtils.addMilliseconds(endVisibilityDate, 1)), is(false));
}

From source file:com.redhat.rhn.domain.action.ActionChainFactory.java

/**
 * Schedules an Action Chain for execution.
 * @param actionChain the action chain to execute
 * @param date first action's minimum timestamp
 *///from w  w  w. j av a  2 s.c  o m
public static void schedule(ActionChain actionChain, Date date) {
    log.debug("Scheduling Action Chain " + actionChain + " to date " + date);
    Map<Server, Action> latest = new HashMap<Server, Action>();
    int maxSortOrder = getNextSortOrderValue(actionChain);
    Date dateInOrder = new Date(date.getTime());

    for (int sortOrder = 0; sortOrder < maxSortOrder; sortOrder++) {
        for (ActionChainEntry entry : getActionChainEntries(actionChain, sortOrder)) {
            Server server = entry.getServer();
            Action action = entry.getAction();

            log.debug("Scheduling Action " + action + " to server " + server);
            ActionFactory.addServerToAction(server.getId(), action);
            action.setPrerequisite(latest.get(server));
            action.setEarliestAction(dateInOrder);

            // Increment 'earliest' time by a millisecond for each chain action in
            // order to sort them correctly for display
            dateInOrder = DateUtils.addMilliseconds(dateInOrder, 1);

            latest.put(server, action);
        }
    }
    log.debug("Action Chain " + actionChain + " scheduled to date " + date + ", deleting");
    delete(actionChain);
}

From source file:ch.ksfx.web.services.chart.ObservationChartGenerator.java

public JFreeChart generateChart(TimeSeries timeSeries, Date startDate, Date endDate) {
    List<Observation> observations = observationDAO.queryObservationsSparse(timeSeries.getId().intValue(),
            startDate, endDate);/* w  ww .  j  a  v  a2 s  .  c  o  m*/

    if (observations == null || observations.size() == 0 || observations.isEmpty()) {
        Observation o = observationDAO.getLastObservationForTimeSeriesId(timeSeries.getId().intValue());
        Long diffInMillis = endDate.getTime() - startDate.getTime();
        startDate = DateUtils.addMilliseconds(o.getObservationTime(), diffInMillis.intValue() * -1);

        System.out.println("[GRAPH] Found 0 Observations trying new query (" + timeSeries.getId() + ") "
                + "Startdate: " + startDate.toString() + " End date: " + endDate.toString());
        observations = observationDAO.queryObservationsSparse(timeSeries.getId().intValue(), startDate,
                DateUtils.addMilliseconds(o.getObservationTime(), 1000));
    }

    System.out
            .println("[GRAPH] Observations size: " + observations.size() + " for (" + timeSeries.getId() + ")");

    //assetPrices = simplifyAssetPrices(assetPrices);

    TimePeriodValues assetPriceTimePeriodValues = new TimePeriodValues(timeSeries.getName());
    TimePeriodValuesCollection dataset = new TimePeriodValuesCollection();

    for (Observation o : observations) {
        assetPriceTimePeriodValues.add(new SimpleTimePeriod(o.getObservationTime(), o.getObservationTime()),
                Double.parseDouble(o.getScalarValue()));
    }

    dataset.addSeries(assetPriceTimePeriodValues);

    JFreeChart jFreeChart = ChartFactory.createXYLineChart("Performance", "Time", "Value", dataset,
            PlotOrientation.VERTICAL, true, false, false);

    setRange(jFreeChart, observations);

    return jFreeChart;
}

From source file:org.alfresco.module.org_alfresco_module_rm.audit.RecordsManagementAuditServiceImpl.java

/**
 * Calculates the end of the given date.
 * For example, if you had the date time of 12 Aug 2013 12:10:15.158
 * the result would be 12 Aug 2013 23:59:59.999.
 *
 * @param date The date for which the end should be calculated.
 * @return Returns the end of the given date.
 *//*from  w  ww . j av  a2s  . c o  m*/
private Date getEndOfDay(Date date) {
    return DateUtils.addMilliseconds(DateUtils.ceiling(date == null ? new Date() : date, Calendar.DATE), -1);
}

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

/**
 * Return a new {@link Date} object that represents the end of the same day as the argument,
 * e.g. 23:59:59.999/*from  www . j  av  a  2 s  .co  m*/
 * 
 * @param date
 * @return a new {@link Date} object that represents the end of the same day as the argument
 */
public static Date endOfDay(Date date) {
    Date local = beginningOfDay(date);
    local = DateUtils.addDays(local, 1);
    local = DateUtils.addMilliseconds(local, -1);
    return local;
}

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

@Override
public PeriodList calculateRecurrence(VEvent event, Date startBoundary, Date endBoundary) {
    Period period = new Period(new DateTime(startBoundary), new DateTime(endBoundary));
    PeriodList periodList = event.calculateRecurrenceSet(period);
    PeriodList results = new PeriodList();
    for (Object o : periodList) {
        Period p = (Period) o;

        if (isAllDayPeriod(p)) {
            // this period is broken
            // the Periods returned by ical4j's calculateRecurrenceSet have range start/ends that are off by the system default's timezone offset
            TimeZone systemTimezone = java.util.TimeZone.getDefault();

            int offset = systemTimezone.getOffset(p.getStart().getTime());
            Period fixed = new Period(new DateTime(DateUtils.addMilliseconds(p.getRangeStart(), -offset)),
                    new DateTime(DateUtils.addMilliseconds(p.getRangeEnd(), -offset)));
            results.add(fixed);//w ww  . j  ava 2s  .  c o m
        } else {
            results.add(p);
        }
    }
    return results;
}

From source file:org.jbpm.migration.upload.Resources.java

/**
 * Convenience method for date handling between time zones.
 * <p>//from w ww  . ja va 2 s .  c  o  m
 * This is only required because the OpenShift server is not in NL!
 *
 * @param date
 *            The given (UTC) date.
 * @return The actual date in NL.
 */
public static Date convertToNLDate(final Date date) {
    return DateUtils.addMilliseconds(date,
            TimeZone.getTimeZone("Europe/Amsterdam").getRawOffset() - TimeZone.getDefault().getRawOffset());
}

From source file:org.jumpmind.metl.core.persist.ExecutionSqlService.java

@Override
protected void purgeExecutions(String status, int retentionTimeInMs) {
    Table table = databasePlatform.readTableFromDatabase(null, null, tableName(Execution.class));
    if (table != null) {
        Date purgeBefore = DateUtils.addMilliseconds(new Date(), -retentionTimeInMs);
        log.debug("Purging executions with the status of {} before {}", status, purgeBefore);
        ISqlTemplate template = databasePlatform.getSqlTemplate();

        List<String> executionStepIds = template.query(String.format(
                "select id from %1$s_execution_step where execution_id in "
                        + "(select id from %1$s_execution where status=? and last_update_time <= ?)",
                tablePrefix), new StringMapper(), new Object[] { status, purgeBefore });
        for (String executionStepId : executionStepIds) {
            File file = new File(LogUtils.getLogDir(), executionStepId + ".log");
            FileUtils.deleteQuietly(file);
        }/*from   w w  w.  j a  va 2 s.  c om*/

        int count = template.update(String.format(
                "delete from %1$s_execution_step where execution_id in "
                        + "(select id from %1$s_execution where status=? and last_update_time <= ?)",
                tablePrefix), status, purgeBefore);
        count += template.update(String
                .format("delete from %1$s_execution where status=? and last_update_time <= ?", tablePrefix),
                status, purgeBefore);
        log.debug("Purged {} execution records with the status of {}", new Object[] { count, status });
        if (!log.isDebugEnabled() && count > 0) {
            log.info("Purged {} execution records", new Object[] { count });
        }
    } else {
        log.info("Could not run execution purge because table had not been created yet");
    }
}