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:com.zimbra.cs.mailbox.calendar.ZRecur.java

/**
 * Very simple function b/c it can completely ignore the Ordinal value
 *
 * @param list/*from  ww w .  j  av a2  s.  co m*/
 * @return
 */
private List<Calendar> expandDayListForWeekly(List<Calendar> list) {
    // this func ONLY works for expanding, NOT for contracting
    assert (mFreq == Frequency.WEEKLY);

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

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

    for (Calendar cur : list) {
        for (ZWeekDayNum day : mByDayList) {
            cur.set(Calendar.DAY_OF_WEEK, day.mDay.getCalendarDay());
            toRet.add((Calendar) (cur.clone()));
        }
    }

    return toRet;
}

From source file:org.everit.jira.timetracker.plugin.JiraTimetrackerWebAction.java

/**
 * Make summary today, this week and this month.
 *
 * @throws GenericEntityException//from  w w  w . java 2s.  c  o  m
 *           GenericEntityException.
 */
public void makeSummary() throws GenericEntityException {
    ApplicationProperties applicationProperties = ComponentAccessor.getApplicationProperties();
    boolean useISO8601 = applicationProperties.getOption(APKeys.JIRA_DATE_TIME_PICKER_USE_ISO8601);

    Calendar startCalendar = Calendar.getInstance();
    if (useISO8601) {
        startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
    }
    startCalendar.setTime(date);
    startCalendar.set(Calendar.HOUR_OF_DAY, 0);
    startCalendar.set(Calendar.MINUTE, 0);
    startCalendar.set(Calendar.SECOND, 0);
    startCalendar.set(Calendar.MILLISECOND, 0);
    Calendar originalStartcalendar = (Calendar) startCalendar.clone();
    Date start = startCalendar.getTime();

    Calendar endCalendar = (Calendar) startCalendar.clone();
    endCalendar.add(Calendar.DAY_OF_MONTH, 1);

    Date end = endCalendar.getTime();
    daySummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, null);
    if ((issuesRegex != null) && !issuesRegex.isEmpty()) {
        dayFilteredSummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, issuesRegex);
    }

    startCalendar = (Calendar) originalStartcalendar.clone();
    while (startCalendar.get(Calendar.DAY_OF_WEEK) != startCalendar.getFirstDayOfWeek()) {
        startCalendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
    }
    start = startCalendar.getTime();
    endCalendar = (Calendar) startCalendar.clone();
    endCalendar.add(Calendar.DATE, DateTimeConverterUtil.DAYS_PER_WEEK);
    end = endCalendar.getTime();
    weekSummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, null);
    if ((issuesRegex != null) && !issuesRegex.isEmpty()) {
        weekFilteredSummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, issuesRegex);
    }

    startCalendar = (Calendar) originalStartcalendar.clone();
    startCalendar.set(Calendar.DAY_OF_MONTH, 1);
    start = startCalendar.getTime();

    endCalendar = (Calendar) originalStartcalendar.clone();
    endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    endCalendar.add(Calendar.DAY_OF_MONTH, 1);
    end = endCalendar.getTime();

    monthSummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, null);
    if ((issuesRegex != null) && !issuesRegex.isEmpty()) {
        monthFilteredSummary = jiraTimetrackerPlugin.summary(selectedUser, start, end, issuesRegex);
    }
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDatePrinter.java

@Override
public <B extends Appendable> B format(Calendar calendar, final B buf) {
    // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored
    if (!calendar.getTimeZone().equals(mTimeZone)) {
        calendar = (Calendar) calendar.clone();
        calendar.setTimeZone(mTimeZone);
    }/*from  w  w  w .  ja  v a2  s.  c o m*/
    return applyRules(calendar, buf);
}

From source file:org.ambraproject.article.action.BrowseArticlesAction.java

private String browseDate() {
    Calendar startDate = Calendar.getInstance();
    startDate.set(Calendar.HOUR_OF_DAY, 0);
    startDate.set(Calendar.MINUTE, 0);
    startDate.set(Calendar.SECOND, 0);
    startDate.set(Calendar.MILLISECOND, 0);

    Calendar endDate;/*from  ww w . j a  v  a  2 s.c  o  m*/

    boolean isLastDay = false;

    if (((startDateParam != null) && startDateParam.length() > 0)
            || ((endDateParam != null) && endDateParam.length() > 0)) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (startDateParam != null) {
                startDate.setTime(sdf.parse(startDateParam));
            } else {
                startDate.setTimeInMillis(0);
            }
            endDate = Calendar.getInstance();
            if (endDateParam != null) {
                endDate.setTime(sdf.parse(endDateParam));
            }
        } catch (Exception e) {
            log.error("Failed to parse start / end Date params");
            return ERROR;
        }
    } else {
        if (getYear() > UNSET && getMonth() > UNSET && getDay() > UNSET) {
            // user has clicked on a date link
            startDate.set(getYear(), getMonth() - 1, getDay());
            endDate = (Calendar) startDate.clone();

        } else if (getYear() > UNSET && getMonth() > UNSET) {
            // user has clicked on a month link
            startDate.set(getYear(), getMonth() - 1, 1);
            endDate = (Calendar) startDate.clone();
            int lastDay = endDate.getActualMaximum(Calendar.DAY_OF_MONTH);
            endDate.set(Calendar.DAY_OF_MONTH, lastDay);

        } else if (getMonth() == PAST_MONTH) {
            // user has clicked on the past month link
            endDate = (Calendar) startDate.clone();
            startDate.add(Calendar.MONTH, -1);

        } else if (getMonth() == PAST_3MON) {
            // user has clicked on the past 3 months link
            endDate = (Calendar) startDate.clone();
            startDate.add(Calendar.MONTH, -3);

        } else if (getDay() == LAST_DAY) {
            // user has clicked on the past day link
            endDate = (Calendar) startDate.clone();
            startDate.add(Calendar.DATE, -1);
            isLastDay = true;
        } else {
            // user has clicked on the past week link
            endDate = (Calendar) startDate.clone();
            startDate.add(Calendar.DATE, -7);
        }
    }
    BrowseParameters params = new BrowseParameters();

    params.setStartDate(startDate);
    params.setEndDate(endDate);
    params.setPageNum(this.startPage);
    params.setPageSize(this.pageSize);
    params.setJournalKey(this.getCurrentJournal());
    params.setSort(this.sort);

    BrowseResult result = browseService.getArticlesByDate(params);

    // want the last day that we have articles published
    if (isLastDay) {
        while (result.getArticles() == null
                || (result.getArticles() != null && result.getArticles().size() == 0)) {
            startDate.add(Calendar.DAY_OF_MONTH, -1);
            params.setStartDate(startDate);
            result = browseService.getArticlesByDate(params);
        }
    }

    this.articleList = result.getArticles();
    this.totalArticles = result.getTotal();
    this.articleDates = browseService.getArticleDatesForJournal(this.getCurrentJournal());
    this.subjectFacet = null;
    //When filtering by date, select all the subjects
    this.subjects = browseService.getSubjectsForJournal(this.getCurrentJournal());

    return SUCCESS;
}

From source file:com.southernstorm.tvguide.TvChannelCache.java

/**
 * Fetch bulk data for all channels.//from w w w  .java 2 s.c o m
 * 
 * @param numDays the number of days to fetch
 * @return true if data has been scheduled to be fetched, false if nothing needs downloading
 */
public boolean bulkFetch(int numDays) {
    boolean fetched = false;
    boolean requestsWereActive = requestsActive;
    Calendar today = new GregorianCalendar();
    for (TvNetworkListener listener : networkListeners)
        listener.setCancelable();
    for (int index = 0; index < activeChannels.size(); ++index) {
        TvChannel channel = activeChannels.get(index);
        for (int day = 0; day < numDays; ++day) {
            Calendar date = (Calendar) today.clone();
            date.add(Calendar.DAY_OF_MONTH, day);
            if (!hasChannelData(channel, date)) {
                fetch(channel, date, today);
                fetched = true;
            }
        }
    }
    if (!fetched && !requestsWereActive) {
        for (TvNetworkListener listener : networkListeners)
            listener.endNetworkRequests();
    }
    return fetched;
}

From source file:com.icesoft.faces.component.selectinputdate.SelectInputDateRenderer.java

private Calendar copyCalendar(FacesContext facesContext, Calendar timeKeeper) {
    Calendar cal = (Calendar) timeKeeper.clone();
    return cal;
}

From source file:com.jarklee.materialdatetimepicker.date.DatePickerDialog.java

private void setToNearestDate(Calendar calendar) {
    if (selectableDays != null) {
        long distance = Long.MAX_VALUE;
        Calendar currentBest = calendar;
        for (Calendar c : selectableDays) {
            long newDistance = Math.abs(calendar.getTimeInMillis() - c.getTimeInMillis());
            if (newDistance < distance && !isDisabled(c)) {
                distance = newDistance;/*from   w  ww. j  a v a2 s.com*/
                currentBest = c;
            } else
                break;
        }
        calendar.setTimeInMillis(currentBest.getTimeInMillis());
        return;
    }

    if (disabledDays != null) {
        Calendar forwardDate = (Calendar) calendar.clone();
        Calendar backwardDate = (Calendar) calendar.clone();
        while (isDisabled(forwardDate) && isDisabled(backwardDate)) {
            forwardDate.add(Calendar.DAY_OF_MONTH, 1);
            backwardDate.add(Calendar.DAY_OF_MONTH, -1);
        }
        if (!isDisabled(backwardDate)) {
            calendar.setTimeInMillis(backwardDate.getTimeInMillis());
            return;
        }
        if (!isDisabled(forwardDate)) {
            calendar.setTimeInMillis(forwardDate.getTimeInMillis());
            return;
        }
    }

    if (isBeforeMin(calendar)) {
        calendar.setTimeInMillis(mMinDate.getTimeInMillis());
        return;
    }

    if (isAfterMax(calendar)) {
        calendar.setTimeInMillis(mMaxDate.getTimeInMillis());
        return;
    }
}

From source file:org.globus.workspace.creation.defaults.CreationManagerImpl.java

protected InstanceResource[] create2(Reservation res, VirtualMachine[] bindings, String callerID,
        Context context, String groupID, String coschedID, String clientToken, boolean spotInstances,
        double chargeRatio)

        throws AuthorizationException, CoSchedulingException, CreationException, MetadataException,
        ResourceRequestDeniedException, SchedulingException {

    // todo: check assumptions (guard against misuse by object extenders)

    // shutdown time is separate from termination time
    // best effort gets null (infinite) termination time: when it
    // starts, the termination time will be adjusted

    Calendar startTime = null;/*from   ww w  .java 2 s . c o m*/
    Calendar stopTime = null;
    Calendar termTime = null;

    if (res.isConcrete()) {

        startTime = res.getStartTime();
        if (startTime == null) {
            throw new SchedulingException("expecting start time if reservation is 'concrete'");
        }

        stopTime = res.getStopTime();
        if (stopTime == null) {
            throw new SchedulingException("expecting start time if reservation is 'concrete'");
        }

        termTime = (Calendar) stopTime.clone();
        termTime.add(Calendar.SECOND, this.globals.getTerminationOffsetSeconds());
    }

    final int[] ids = res.getIds();
    if (ids == null) {
        throw new SchedulingException("expecting ID assignments from reservation");
    }

    final InstanceResource[] createdResources = new InstanceResource[ids.length];

    int bailed = -1;
    Throwable failure = null;
    for (int i = 0; i < ids.length; i++) {

        try {
            createdResources[i] = this.createOne(i, ids, res, bindings[i], callerID, context, coschedID,
                    groupID, clientToken, startTime, termTime, chargeRatio);
        } catch (Throwable t) {
            bailed = i;
            failure = t;
            break;
        }

    }

    if (failure != null) {

        // always throws an exception, return is to satisfy compiler
        return this.failure(ids, bailed, failure);

    } else {

        final boolean eventLog = this.lager.eventLog;
        final boolean debugLog = logger.isDebugEnabled();

        if (eventLog || debugLog) {
            this.successPrint(eventLog, debugLog, startTime, stopTime, termTime, bindings[0].getName(),
                    callerID, ids.length, ids, groupID, coschedID, res);
        }

        // go:
        this.schedulerCreatedNotification(ids, spotInstances);

        return createdResources;
    }
}

From source file:org.sakaiproject.tool.summarycalendar.ui.CalendarBean.java

private CalendarEventVector getEventsFromSchedule() {
    if (calendarEventVector == null) {
        Calendar firstDay;
        Calendar lastDay;/*from w w  w .  j  a  va2 s .c o  m*/

        if (viewMode.equals(MODE_WEEKVIEW)) {
            // WEEK VIEW

            // select first day
            firstDay = Calendar.getInstance(getCurrentUserTimezone(), msgs.getLocale());
            firstDay.setTime(getViewingDate());
            firstDay.set(Calendar.HOUR_OF_DAY, 0);
            firstDay.set(Calendar.MINUTE, 0);
            firstDay.set(Calendar.SECOND, 0);
            firstDay.set(Calendar.MILLISECOND, 0);
            int dayOfWeek = firstDay.get(Calendar.DAY_OF_WEEK);
            // TODO Allow dynamic choice of first day of week
            while (dayOfWeek != Calendar.SUNDAY) {
                firstDay.add(Calendar.DAY_OF_WEEK, -1);
                dayOfWeek = firstDay.get(Calendar.DAY_OF_WEEK);
            }

            // select last day
            lastDay = (Calendar) firstDay.clone();
            lastDay.add(Calendar.DAY_OF_WEEK, 6);
            lastDay.set(Calendar.HOUR_OF_DAY, 23);
            lastDay.set(Calendar.MINUTE, 59);
            lastDay.set(Calendar.SECOND, 59);
            lastDay.set(Calendar.MILLISECOND, 999);
        } else {
            // MONTH VIEW

            // select first day
            firstDay = Calendar.getInstance(getCurrentUserTimezone(), msgs.getLocale());
            firstDay.setTime(getViewingDate());
            int selYear = firstDay.get(Calendar.YEAR);
            int selMonth = firstDay.get(Calendar.MONTH);
            firstDay.set(Calendar.YEAR, selYear);
            firstDay.set(Calendar.DAY_OF_MONTH, 1);
            firstDay.set(Calendar.HOUR_OF_DAY, 0);
            firstDay.set(Calendar.MINUTE, 0);
            firstDay.set(Calendar.SECOND, 0);
            firstDay.set(Calendar.MILLISECOND, 0);
            int dayOfWeek = firstDay.get(Calendar.DAY_OF_WEEK);
            // TODO Allow dynamic choice of first day of week
            while (dayOfWeek != Calendar.SUNDAY) {
                firstDay.add(Calendar.DAY_OF_WEEK, -1);
                dayOfWeek = firstDay.get(Calendar.DAY_OF_WEEK);
            }

            // select last day
            lastDay = (Calendar) firstDay.clone();
            lastDay.set(Calendar.YEAR, selYear);
            lastDay.set(Calendar.MONTH, selMonth);
            lastDay.set(Calendar.DAY_OF_MONTH, lastDay.getActualMaximum(Calendar.DAY_OF_MONTH));
            lastDay.set(Calendar.HOUR_OF_DAY, 23);
            lastDay.set(Calendar.MINUTE, 59);
            lastDay.set(Calendar.SECOND, 59);
            lastDay.set(Calendar.MILLISECOND, 999);
            dayOfWeek = lastDay.get(Calendar.DAY_OF_WEEK);
            // TODO Allow dynamic choice of first day of week
            while (dayOfWeek != Calendar.SATURDAY) {
                lastDay.add(Calendar.DAY_OF_WEEK, 1);
                dayOfWeek = lastDay.get(Calendar.DAY_OF_WEEK);
            }
        }

        Time firstTime = M_ts.newTime(firstDay.getTimeInMillis());
        Time lastTime = M_ts.newTime(lastDay.getTimeInMillis());
        TimeRange range = M_ts.newTimeRange(firstTime, lastTime);
        calendarEventVector = M_ca.getEvents(getCalendarReferences(), range);
    }
    return calendarEventVector;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * Creates the algo control list.//from  w  ww . j  av  a 2  s .  c  om
 * @param jobData the job data
 * @param thermostatId the thermostat id
 * @param algoId the algo id
 * @return the list
 */
protected List<ThermostatAlgorithmController> createAlgoControlList(JSONArray jobData, Integer thermostatId,
        Integer algoId) {

    Algorithm algorithm = findByAlgorithmId(algoId);
    List<ThermostatAlgorithmController> algoControlList = new ArrayList<ThermostatAlgorithmController>();

    int moBlackOut;
    double moRecovery;
    double deltaEE = 0;
    Calendar utcCalendar = null;
    Calendar startTime = null;
    Calendar endTime = null;
    Calendar moCutoffTime = null;
    JSONObject jsonObj;

    for (int i = 0; i < jobData.length(); i++) {

        try {

            jsonObj = jobData.getJSONObject(i);
            startTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("start"));
            endTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("end"));
            moCutoffTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("moCutoff"));

            moBlackOut = jsonObj.getInt("moBlackOut");
            moRecovery = jsonObj.getInt("moRecovery");
            deltaEE = jsonObj.getDouble("deltaEE");

            ThermostatAlgorithmController algoControlPhase1 = new ThermostatAlgorithmController();
            algoControlPhase1.setStatus(Status.ACTIVE);
            algoControlPhase1.setThermostatId(thermostatId);
            algoControlPhase1.setAlgorithmId(algoId);

            String utcCalendarTimeStamp = DateUtil.format(startTime, DateUtil.DATE_FMT_FULL);
            utcCalendar = DateUtil.parseToCalendar(utcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Next phase time
            algoControlPhase1.setNextPhaseTime(utcCalendar);

            // Execution start time.
            Calendar executionStartTime = (Calendar) utcCalendar.clone();
            executionStartTime.add(Calendar.MINUTE, -3);
            algoControlPhase1.setExecutionStartTimeUTC(executionStartTime);

            String endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            Calendar endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            // Execution end time.
            algoControlPhase1.setExecutionEndTimeUTC(endutcCalendar);

            String cuttoffutcCalendarTimeStamp = DateUtil.format(moCutoffTime, DateUtil.DATE_FMT_FULL);
            Calendar cutOffutcCalendar = DateUtil.parseToCalendar(cuttoffutcCalendarTimeStamp,
                    DateUtil.DATE_FMT_FULL);

            // MO cut off time.
            algoControlPhase1.setMoCutOff(cutOffutcCalendar);

            algoControlPhase1.setPhase0Spt(deltaEE);
            algoControlPhase1.setPrevSpt(0.0);
            algoControlPhase1.setMoBlackOut(moBlackOut);
            algoControlPhase1.setMoRecovery(moRecovery);
            algoControlPhase1.setAlgorithm(algorithm);
            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase1.setActor(ACTOR_SPO);
            }

            algoControlList.add(algoControlPhase1);
            // second row
            ThermostatAlgorithmController algoControlPhase2 = new ThermostatAlgorithmController();

            algoControlPhase2 = algoControlPhase1.clone();

            endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL);
            endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL);

            if (algoId == SPO_COOL || algoId == SPO_HEAT) {
                algoControlPhase2.setActor(ACTOR_SPO);
            }
            // Execution end time.
            algoControlPhase2.setExecutionStartTimeUTC(endutcCalendar);
            algoControlPhase2.setExecutionEndTimeUTC(null);
            algoControlPhase2.setNextPhaseTime(endutcCalendar);
            algoControlPhase2.setPhase0Spt(0.0);
            algoControlPhase2.setAlgorithm(algorithm);
            algoControlPhase2.setStatus(Status.ACTIVE);
            algoControlList.add(algoControlPhase2);

        } catch (JSONException | CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
    return algoControlList;
}