Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:nl.strohalm.cyclos.services.accounts.AccountServiceImpl.java

private AccountStatus getStatusAt(final Account account, final Calendar date,
        final boolean onlyIfThereAreDiffs) {
    // Fill the status with basic data
    AccountStatus status = new AccountStatus();
    status.setAccount(account);/*from   www. j a  v a  2  s  .com*/
    status.setCreditLimit(account.getCreditLimit());
    status.setUpperCreditLimit(account.getUpperCreditLimit());
    status.setDate(date);

    // Get the last closed balance
    ClosedAccountBalance closedBalance = closedAccountBalanceDao.get(account, date);
    Calendar closedDate = closedBalance == null ? null : closedBalance.getDate();
    Calendar endDate = (Calendar) (date == null ? null : date.clone());
    if (endDate != null) {
        endDate.add(Calendar.SECOND, -1);
    }
    Period period = Period.between(closedDate, endDate);

    // Get the balance diff
    BigDecimal balanceDiff = transferDao.balanceDiff(account, period);
    status.setBalance(closedBalance == null ? balanceDiff : closedBalance.getBalance().add(balanceDiff));

    // Get the reserved amount diff
    BigDecimal reservationDiff = amountReservationDao.reservationDiff(account, period);
    status.setReservedAmount(
            closedBalance == null ? reservationDiff : closedBalance.getReserved().add(reservationDiff));

    if (onlyIfThereAreDiffs && balanceDiff.equals(BigDecimal.ZERO) && reservationDiff.equals(BigDecimal.ZERO)) {
        // If should return only if there are diffs, and there were none, return null
        return null;
    }

    return status;

}

From source file:com.samsistemas.calendarview.widget.CalendarView.java

/**
 * This method prepare and populate the days in the CalendarView
 *//*from   ww w  .j a v  a2s  .  c  o  m*/
private void setDaysInCalendar() {
    Calendar calendar = Calendar.getInstance(getLocale());
    calendar.setTime(mCalendar.getTime());
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.setFirstDayOfWeek(mFirstDayOfWeek);
    int firstDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);

    // Calculate dayOfMonthIndex
    int dayOfMonthIndex = CalendarUtility.getWeekIndex(firstDayOfMonth, calendar);
    int actualMaximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    final Calendar startCalendar = (Calendar) calendar.clone();
    //Add required number of days
    startCalendar.add(Calendar.DATE, -(dayOfMonthIndex - 1));
    int monthEndIndex = 42 - (actualMaximum + dayOfMonthIndex - 1);

    DayView dayView;
    ViewGroup dayOfMonthContainer;
    for (int i = 1; i < 43; i++) {
        dayOfMonthContainer = (ViewGroup) mView
                .findViewWithTag(mContext.getString(R.string.day_of_month_container) + i);
        dayView = (DayView) mView.findViewWithTag(mContext.getString(R.string.day_of_month_text) + i);
        if (dayView == null)
            continue;

        //Apply the default styles
        dayOfMonthContainer.setOnClickListener(null);
        dayView.bind(startCalendar.getTime(), getDecoratorsList());
        dayView.setVisibility(View.VISIBLE);

        if (null != getTypeface()) {
            dayView.setTypeface(getTypeface());
        }

        if (CalendarUtility.isSameMonth(calendar, startCalendar)) {
            dayOfMonthContainer.setOnClickListener(onDayOfMonthClickListener);
            dayOfMonthContainer.setOnLongClickListener(onDayOfMonthLongClickListener);
            dayView.setBackgroundColor(mCalendarBackgroundColor);
            mIsCommonDay = true;
            if (totalDayOfWeekend().length != 0) {
                for (int weekend : totalDayOfWeekend()) {
                    if (startCalendar.get(Calendar.DAY_OF_WEEK) == weekend) {
                        dayView.setTextColor(mWeekendColor);
                        mIsCommonDay = false;
                    }
                }
            }

            if (mIsCommonDay) {
                dayView.setTextColor(mDayOfWeekTextColor);
            }
        } else {
            dayView.setBackgroundColor(mDisabledDayBackgroundColor);
            dayView.setTextColor(mDisabledDayTextColor);

            if (!isOverflowDateVisible())
                dayView.setVisibility(View.GONE);
            else if (i >= 36 && ((float) monthEndIndex / 7.0f) >= 1) {
                dayView.setVisibility(View.GONE);
            }
        }
        dayView.decorate();

        //Set the current day color
        if (mCalendar.get(Calendar.MONTH) == startCalendar.get(Calendar.MONTH))
            setCurrentDay(mCalendar.getTime());

        startCalendar.add(Calendar.DATE, 1);
        dayOfMonthIndex++;
    }

    // If the last week row has no visible days, hide it or show it in case
    ViewGroup weekRow = (ViewGroup) mView.findViewWithTag("weekRow6");
    dayView = (DayView) mView.findViewWithTag("dayOfMonthText36");
    if (dayView.getVisibility() != VISIBLE) {
        weekRow.setVisibility(GONE);
    } else {
        weekRow.setVisibility(VISIBLE);
    }
}

From source file:nz.co.jsrsolutions.ds3.command.UpdateExchangeQuotesCommand.java

public boolean execute(Context context) throws Exception {

    logger.info("Executing: updateexchangequotes");

    final String exchange = (String) context.get(CommandContext.EXCHANGE_KEY);

    if (exchange == null) {
        throw new CommandException("Must supply --exchange [exchangecode]");
    }/*  w  ww  .j av  a2 s. c o  m*/

    long nQuotesWritten = 0;

    final int availableMonths = _eodDataProvider.getExchangeMonths(exchange);

    final String[] symbols = _eodDataSink.readExchangeSymbols(exchange);

    if (symbols == null) {
        logger.info("No symbols associated with this exchange...");
        return false;
    }

    final Collection<Future<Long>> futures = new LinkedList<Future<Long>>();

    for (String symbol : symbols) {

        final Calendar firstAvailableDateTime = Calendar.getInstance();

        if (availableMonths > 0) {
            firstAvailableDateTime.add(Calendar.MONTH, -1 * availableMonths);
            firstAvailableDateTime.add(Calendar.DATE, 1);
        }

        final Calendar today = Calendar.getInstance();

        final Range<Calendar> sinkRange = _eodDataSink.readExchangeSymbolDateRange(exchange, symbol);

        final ArrayList<Range<Calendar>> requestRangesList = new ArrayList<Range<Calendar>>(2);

        if (sinkRange != null) {

            if (firstAvailableDateTime.compareTo(sinkRange.getLower()) < 0) {

                // In this implementation we can't ask for this!

                /*      
                       final Calendar upper = (Calendar) sinkRange.getLower().clone();
                       upper.add(Calendar.DATE, -1);
                       final Calendar lower = (firstAvailableDateTime.compareTo(upper) < 0) ? firstAvailableDateTime : upper;
                               
                       requestRangesList.add(new Range<Calendar>(firstAvailableDateTime,
                           upper));
                                  
                       // TODO: implement prepend in Hd5 Sink
                */
            }

            if (today.compareTo(sinkRange.getUpper()) > 0) {

                final Calendar lower = (Calendar) sinkRange.getUpper().clone();
                lower.add(Calendar.DATE, 1);
                // TODO: fix this by observing timezones
                final Calendar upper = (Calendar) today.clone();
                // cheat for now with upper bound on today (anywhere in the world!)
                upper.add(Calendar.DATE, 1);

                requestRangesList.add(new Range<Calendar>(lower, upper));

            }

        } else {
            requestRangesList.add(new Range<Calendar>(firstAvailableDateTime, today));
        }

        for (Range<Calendar> requestRange : requestRangesList) {

            if (logger.isInfoEnabled()) {

                StringBuffer logMessageBuffer = new StringBuffer();
                logMessageBuffer.setLength(0);
                logMessageBuffer.append(" Attempting to retrieve quotes on [ ");
                logMessageBuffer.append(exchange);
                logMessageBuffer.append(" ] for [ ");
                logMessageBuffer.append(symbol);
                logMessageBuffer.append(" ] between [ ");
                logMessageBuffer.append(requestRange.getLower().getTime().toString());
                logMessageBuffer.append(" ] and [ ");
                logMessageBuffer.append(requestRange.getUpper().getTime().toString());
                logMessageBuffer.append(" ] ");
                logger.info(logMessageBuffer.toString());

            }

            try {

                futures.add(_executorService.submit(new ReadWriteQuotesTask(_eodDataProvider, _eodDataSink,
                        exchange, symbol, requestRange.getLower(), requestRange.getUpper())));

            } catch (Exception e) {
                logger.error("Task submission failed", e);
            }

        }

    }

    for (Future<Long> future : futures) {
        try {
            nQuotesWritten += future.get();
        } catch (ExecutionException e) {
            logger.error("Execution exception: ", e);
        } catch (InterruptedException e) {
            logger.error("Interrupted exception: ", e);
        }
    }

    if (_emailService != null) {
        final StringBuffer subjectBuffer = new StringBuffer();
        subjectBuffer.append("Updated quotes on ");
        subjectBuffer.append(exchange);

        final StringBuffer messageBuffer = new StringBuffer();
        messageBuffer.append("Wrote ");
        messageBuffer.append(nQuotesWritten);
        messageBuffer.append(" quotes over ");
        messageBuffer.append(symbols.length);
        messageBuffer.append(" symbols ");

        _emailService.send(subjectBuffer.toString(), messageBuffer.toString());
    }

    return false;

}

From source file:nl.strohalm.cyclos.services.access.AccessServiceImpl.java

@Override
public void purgeTraces(final Calendar time) {
    Calendar limit = (Calendar) time.clone();
    limit.add(Calendar.DAY_OF_MONTH, -1);
    wrongCredentialAttemptsDao.clear(limit);
    wrongUsernameAttemptsDao.clear(limit);
    permissionDeniedTraceDao.clear(limit);
}

From source file:org.apache.stratos.usage.api.TenantUsageRetriever.java

public APIManagerUsageStats[] getAPIManagerUsageStats(int tenantId, Calendar startDate, Calendar endDate,
        boolean currentMonth) throws Exception {
    //return the bandwidth usage of a user for a given period
    APIManagerUsageStats[] stats;//from   ww w . ja v  a2s . com
    if (currentMonth) {
        //get from daily usage stats
        List<APIManagerUsageStats> bwsList = new ArrayList<APIManagerUsageStats>();
        bwsList = dao.getDailyAPIManagerUsageStats(tenantId, startDate, endDate);

        //next we'll get from the houlry stats to get the stats which are not yet
        //summarized to the daily stats table
        Calendar startHour = Calendar.getInstance();
        startHour.set(Calendar.HOUR, 0);
        startHour.set(Calendar.MINUTE, 0);
        startHour.set(Calendar.SECOND, 0);

        Calendar endHour = Calendar.getInstance();

        bwsList.addAll(dao.getHourlyAPIManagerUsageStats(tenantId, startHour, endHour));
        stats = convertAPIStatListToArray(bwsList);

    } else {
        //get from monthly usage stats
        Calendar monthCal = (Calendar) endDate.clone();
        monthCal.set(Calendar.DATE, 0);
        monthCal.set(Calendar.HOUR, 0);
        monthCal.set(Calendar.MINUTE, 0);
        monthCal.set(Calendar.SECOND, 0);

        stats = convertAPIStatListToArray(dao.getMonthlyAPIManagerUsageStats(tenantId, monthCal));
    }
    HashMap<String, APIManagerUsageStats> statMap = new HashMap<String, APIManagerUsageStats>();
    if (stats != null) {
        for (APIManagerUsageStats stat : stats) {
            if (stat.getRequestCount() == 0) {
                continue;
            }
            String serverName = extractServiceNameFromUrl(stat.getServerUrl());
            String statName = stat.getKey();

            HashMap<String, APIManagerUsageStats> statsHashMap;
            if (statName.equals("API-Call")) {
                statsHashMap = statMap;
            } else {
                log.warn("Unable to identify bandwidth name " + statName);
                continue;
            }

            //find whether the map already has this key; If not, insert a new one
            APIManagerUsageStats reqStat = statsHashMap.get(serverName);
            if (reqStat == null) {
                reqStat = new APIManagerUsageStats(serverName);
                statsHashMap.put(serverName, reqStat);
            }
            reqStat.setRequestCount(stat.getRequestCount());
        }
    }

    //Convert to array and return it
    APIManagerUsageStats[] returnValue = new APIManagerUsageStats[0];
    Collection<APIManagerUsageStats> values = statMap.values();
    returnValue = values.toArray(new APIManagerUsageStats[values.size()]);
    return returnValue;
}

From source file:org.apache.stratos.usage.api.TenantUsageRetriever.java

public BandwidthStatistics[][] getBandwidthStatistics(int tenantId, Calendar startDate, Calendar endDate,
        boolean currentMonth) throws Exception {
    //return the bandwidth usage of a user for a given period
    BandwidthStatistics[] stats;//from   w w w . j  a v a2s  .c o  m
    if (currentMonth) {
        //get from daily usage stats
        List<BandwidthStatistics> bwsList = new ArrayList<BandwidthStatistics>();
        bwsList = dao.getDailyBandwidthStats(tenantId, startDate, endDate);

        //next we'll get from the houlry stats to get the stats which are not yet
        //summarized to the daily stats table
        Calendar startHour = Calendar.getInstance();
        startHour.set(Calendar.HOUR, 0);
        startHour.set(Calendar.MINUTE, 0);
        startHour.set(Calendar.SECOND, 0);

        Calendar endHour = Calendar.getInstance();

        bwsList.addAll(dao.getHourlyBandwidthStats(tenantId, startHour, endHour));
        stats = convertBWListToArray(bwsList);

    } else {
        //get from monthly usage stats
        Calendar monthCal = (Calendar) endDate.clone();
        monthCal.set(Calendar.DATE, 0);
        monthCal.set(Calendar.HOUR, 0);
        monthCal.set(Calendar.MINUTE, 0);
        monthCal.set(Calendar.SECOND, 0);

        stats = convertBWListToArray(dao.getMonthlyBandwidthStats(tenantId, monthCal));
    }

    // store the statistics in a temporary map. This is because, we are getting the server name
    // from the URL and there might be two distinct URL gives same server name.
    // For example, http://esb.a.b/ and http://esb.c.d/ both will give the server name as "esb"
    // Hence, the value should be accumulated value
    HashMap<String, BandwidthStatistics> regBwMap = new HashMap<String, BandwidthStatistics>();
    HashMap<String, BandwidthStatistics> svcBwMap = new HashMap<String, BandwidthStatistics>();
    HashMap<String, BandwidthStatistics> webappBwMap = new HashMap<String, BandwidthStatistics>();

    if (stats != null) {
        for (BandwidthStatistics stat : stats) {
            //Proceed only if incoming bandwidth or outgoing bandwidth is not zero
            if (stat.getIncomingBandwidth() == 0 && stat.getOutgoingBandwidth() == 0) {
                continue;
            }

            //TODO: fix the extractServiceUrl method properly
            String serverName = extractServiceNameFromUrl(stat.getServerUrl());
            String bandwidthName = stat.getKey();

            HashMap<String, BandwidthStatistics> bwMap;
            if (bandwidthName.equals(UsageConstants.REGISTRY_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.REGISTRY_OUTGOING_BW)) {
                bwMap = regBwMap;
            } else if (bandwidthName.equals(UsageConstants.SERVICE_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.SERVICE_OUTGOING_BW)) {
                bwMap = svcBwMap;
            } else if (bandwidthName.equals(UsageConstants.WEBAPP_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.WEBAPP_OUTGOING_BW)) {
                bwMap = webappBwMap;
            } else {
                log.warn("Unable to identify bandwidth name " + bandwidthName);
                continue;
            }

            //find whether the map already has this key; If not, insert a new one
            BandwidthStatistics reqStat = bwMap.get(serverName);
            if (reqStat == null) {
                reqStat = new BandwidthStatistics(serverName);
                bwMap.put(serverName, reqStat);
            }

            // Update the service specific statistics
            reqStat.setIncomingBandwidth(reqStat.getIncomingBandwidth() + stat.getIncomingBandwidth());
            reqStat.setOutgoingBandwidth(reqStat.getOutgoingBandwidth() + stat.getOutgoingBandwidth());
        }
    }

    //Convert to array and return it
    BandwidthStatistics[][] returnValue = new BandwidthStatistics[3][];
    Collection<BandwidthStatistics> values = regBwMap.values();
    returnValue[REG_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);
    values = svcBwMap.values();
    returnValue[SVC_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);
    values = webappBwMap.values();
    returnValue[WEBAPP_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);

    return returnValue;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private List<Calendar> expandHourList(List<Calendar> list) {
    // this func ONLY works for expanding, NOT for contracting
    assert (mFreq == Frequency.DAILY || mFreq == Frequency.WEEKLY || mFreq == Frequency.MONTHLY
            || mFreq == Frequency.YEARLY);

    if (mByHourList.size() <= 0)
        return list;

    List<Calendar> toRet = new LinkedList<Calendar>();

    for (Calendar cur : list) {
        for (Integer hour : mByHourList) {
            cur.set(Calendar.HOUR_OF_DAY, hour);
            toRet.add((Calendar) (cur.clone()));
        }/*from   w w  w. j  ava 2 s  . c  o m*/
    }

    return toRet;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private List<Calendar> expandMinuteList(List<Calendar> list) {
    // this func ONLY works for expanding, NOT for contracting
    assert (mFreq != Frequency.MINUTELY && mFreq != Frequency.SECONDLY);

    if (mByMinuteList.size() <= 0)
        return list;

    List<Calendar> toRet = new LinkedList<Calendar>();

    for (Calendar cur : list) {
        for (Integer minute : mByMinuteList) {
            cur.set(Calendar.MINUTE, minute);
            toRet.add((Calendar) (cur.clone()));
        }/*from  w  w  w  .j a va  2 s . c  o  m*/
    }

    return toRet;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private List<Calendar> expandSecondList(List<Calendar> list) {
    // this func ONLY works for expanding, NOT for contracting
    assert (mFreq != Frequency.SECONDLY);

    if (mBySecondList.size() <= 0)
        return list;

    List<Calendar> toRet = new LinkedList<Calendar>();

    for (Calendar cur : list) {
        for (Integer second : mBySecondList) {
            cur.set(Calendar.SECOND, second);
            toRet.add((Calendar) (cur.clone()));
        }//w w  w. j  av  a2s. c om
    }

    return toRet;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private List<Calendar> expandMonthList(List<Calendar> list) {
    // this func ONLY works for expanding, NOT for contracting
    assert (mFreq == Frequency.YEARLY);

    if (mByMonthList.size() <= 0)
        return list;

    List<Calendar> toRet = new LinkedList<Calendar>();

    for (Calendar cur : list) {
        for (Integer month : mByMonthList) {
            cur.set(Calendar.MONTH, month - 1);

            toRet.add((Calendar) (cur.clone()));
        }/*w w  w.ja v  a 2 s.c  o m*/
    }

    return toRet;
}