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.application.ApplicationServiceImpl.java

@Override
public void purgeIndexOperations(final Calendar time) {
    Calendar limit = (Calendar) time.clone();
    limit.add(Calendar.HOUR_OF_DAY, -24);
    indexOperationDao.deleteBefore(limit);
}

From source file:org.kuali.kfs.module.purap.batch.service.impl.PurapRunDateServiceImpl.java

/**
 * Determines if the given calendar time is before the given cutoff time
 * /*from  w  w w  .  j  ava2s.  c om*/
 * @param currentCal the current time
 * @param cutoffTime the "start of the day" cut off time
 * @return true if the current time is before the cutoff, false otherwise
 */
protected boolean isCurrentDateAfterCutoff(Calendar currentCal, CutoffTime cutoffTime) {
    if (cutoffTime != null) {
        // if cutoff date is not properly defined
        // 24 hour clock (i.e. hour is 0 - 23)

        // clone the calendar so we get the same month, day, year
        // then change the hour, minute, second fields
        // then see if the cutoff is before or after
        Calendar cutoffCal = (Calendar) currentCal.clone();
        cutoffCal.setLenient(false);
        cutoffCal.set(Calendar.HOUR_OF_DAY, cutoffTime.hour);
        cutoffCal.set(Calendar.MINUTE, cutoffTime.minute);
        cutoffCal.set(Calendar.SECOND, cutoffTime.second);
        cutoffCal.set(Calendar.MILLISECOND, 0);

        return currentCal.after(cutoffCal);
    }
    // if cutoff date is not properly defined, then it is considered to be before the cutoff, that is, no cutoff date will be applied
    return false;
}

From source file:gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository.java

/**
 * Gets the list of data audit events for a domain object.
 *
 * @param entityClass the entity class//from   w ww. j av  a  2 s.  c  om
 * @param entityId    the entity id
 * @param calendar    the calendar
 * @return the list of data audit events
 */
@SuppressWarnings("unchecked")
private List<DataAuditEvent> getDataAuditEvents(final Class entityClass, final Integer entityId,
        final Calendar calendar) {

    DataAuditEventQuery dataAuditEventQuery = new DataAuditEventQuery();
    dataAuditEventQuery.leftJoinFetch("e.values");

    dataAuditEventQuery.filterByClassName(entityClass.getName());
    dataAuditEventQuery.filterByEntityId(entityId);

    if (calendar != null) {
        final Calendar newCalendar = (Calendar) calendar.clone();
        newCalendar.add(Calendar.DAY_OF_MONTH, +1);
        Date startDate = DateUtils.truncate(calendar.getTime(), Calendar.DATE);
        Date endDate = DateUtils.truncate(newCalendar.getTime(), Calendar.DATE);
        dataAuditEventQuery.filterByStartDateAfter(startDate);
        dataAuditEventQuery.filterByEndDateBefore(endDate);

    }
    final List<DataAuditEvent> dataAuditEvents = auditHistoryDao.findDataAuditEvents(dataAuditEventQuery);

    return dataAuditEvents;

}

From source file:org.apache.hawq.pxf.plugins.ignite.IgnitePartitionFragmenter.java

/**
 * Returns list of fragments for Ignite table queries
 *
 * @throws UnsupportedOperationException if a partition of unknown type was found
 *
 * @return a list of fragments//from   w  ww.  j  a v  a2s  .  c om
 */
@Override
public List<Fragment> getFragments() throws UnsupportedOperationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getFragments() called; dataSource is '" + inputData.getDataSource() + "'");
    }

    byte[] fragmentMetadata = null;
    byte[] fragmentUserdata = null;

    if (partitionType == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found no partition");
        }
        Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped, fragmentMetadata,
                fragmentUserdata);
        fragments.add(fragment);
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() successful");
        }
        return fragments;
    }

    switch (partitionType) {
    case DATE: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found DATE partition");
        }
        int currInterval = intervalNum;

        Calendar fragStart = rangeStart;
        while (fragStart.before(rangeEnd)) {
            Calendar fragEnd = (Calendar) fragStart.clone();
            switch (intervalType) {
            case DAY:
                fragEnd.add(Calendar.DAY_OF_MONTH, currInterval);
                break;
            case MONTH:
                fragEnd.add(Calendar.MONTH, currInterval);
                break;
            case YEAR:
                fragEnd.add(Calendar.YEAR, currInterval);
                break;
            }
            if (fragEnd.after(rangeEnd))
                fragEnd = (Calendar) rangeEnd.clone();

            fragmentMetadata = new byte[16];
            ByteUtils.toLittleEndian(fragmentMetadata, fragStart.getTimeInMillis(), 0, 8);
            ByteUtils.toLittleEndian(fragmentMetadata, fragEnd.getTimeInMillis(), 8, 8);
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);

            fragments.add(fragment);

            // Continue the previous fragment
            fragStart = fragEnd;
        }
        break;
    }
    case INT: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found INT partition");
        }
        int rangeStart = Integer.parseInt(range[0]);
        int rangeEnd = Integer.parseInt(range[1]);
        int currInterval = intervalNum;

        int fragStart = rangeStart;
        while (fragStart < rangeEnd) {
            int fragEnd = fragStart + currInterval;
            if (fragEnd > rangeEnd) {
                fragEnd = rangeEnd;
            }

            fragmentMetadata = new byte[8];
            ByteUtils.toLittleEndian(fragmentMetadata, fragStart, 0, 4);
            ByteUtils.toLittleEndian(fragmentMetadata, fragEnd, 4, 4);
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);

            fragments.add(fragment);

            // Continue the previous fragment
            fragStart = fragEnd;
        }
        break;
    }
    case ENUM: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found ENUM partition");
        }
        for (String frag : range) {
            fragmentMetadata = frag.getBytes();
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);
            fragments.add(fragment);
        }
        break;
    }
    default: {
        throw new UnsupportedOperationException("getFragments() found a partition of unknown type and failed");
    }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getFragments() successful");
    }
    return fragments;
}

From source file:gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository.java

/**
 * Checks if entity was created minutes before the specefied date.
 * By default method will check if entity was created one minute before the given data
 *
 * @param entityClass the entity class// w  ww.java 2  s.c o  m
 * @param entityId    the primary key of entity
 * @param calendar    the date
 * @param minutes     time before the entity was created
 * @return true if entity was created minutes before the specefied date.
 * @throws IllegalArgumentException if all the parameter except minutes is null;
 */
public boolean checkIfEntityWasCreatedMinutesBeforeSpecificDate(final Class entityClass, final Integer entityId,
        final Calendar calendar, int minutes)

{

    if (calendar == null || entityClass == null || entityId == null) {
        throw new IllegalArgumentException("invalid uses of method. All method parameters must not be null");
    }
    if (Integer.valueOf(minutes).equals(Integer.valueOf(0))) {
        minutes = 1;
    }
    final Calendar newCalendar = (Calendar) calendar.clone();
    newCalendar.add(Calendar.MINUTE, -minutes);
    DataAuditEventQuery dataAuditEventQuery = new DataAuditEventQuery();
    dataAuditEventQuery.filterByClassName(entityClass.getName());
    dataAuditEventQuery.filterByStartDateAfter(newCalendar.getTime());
    dataAuditEventQuery.filterByEndDateBefore(calendar.getTime());
    dataAuditEventQuery.filterByEntityId(entityId);
    dataAuditEventQuery.filterByOperation(Operation.CREATE);
    final List<DataAuditEvent> dataAuditEvents = auditHistoryDao.findDataAuditEvents(dataAuditEventQuery);
    return dataAuditEvents != null && !dataAuditEvents.isEmpty();

}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeTime.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }/*from  w  w w  .j av  a 2 s.c o m*/

    // set date to 01.01.1970
    calendar = (Calendar) calendar.clone();
    calendar.set(1970, 0, 1);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.SECOND))[0],
                    bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.MINUTE))[0],
                    bcdType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.SECOND))[0],
                    charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.MINUTE))[0],
                    charType.encode(calendar.get(Calendar.HOUR_OF_DAY))[0] };

        } else if (StringUtils.equals(variant, MINUTES) || StringUtils.equals(variant, MINUTES_SHORT)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1970, 0, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            long millisMidnight = calendar.getTimeInMillis();

            BigDecimal minutes = new BigDecimal(millis - millisMidnight);

            // milliseconds to minutes
            minutes = minutes.divide(BigDecimal.valueOf(1000 * 60), 0, RoundingMode.HALF_UP);

            // xxx
            minutes = minutes.divide(minuteMultiplier, 0, RoundingMode.HALF_UP);

            if (StringUtils.equals(variant, MINUTES_SHORT)) {
                result = charType.encode(minutes);
            } else {
                result = wordType.encode(minutes);
            }

        }
    }

    return result;
}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeDate.java

@Override
public byte[] encodeInt(Object data) throws EBusTypeException {

    IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
    IEBusType<BigDecimal> wordType = types.getType(EBusTypeWord.TYPE_WORD);
    IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);

    Calendar calendar = null;
    byte[] result = new byte[this.getTypeLength()];

    if (data instanceof EBusDateTime) {
        calendar = ((EBusDateTime) data).getCalendar();

    } else if (data instanceof Calendar) {
        calendar = (Calendar) data;
    }/*from w  w w . j  a va2 s.  co m*/

    // set date to midnight
    calendar = (Calendar) calendar.clone();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    if (calendar != null) {
        if (StringUtils.equals(variant, DEFAULT)) {

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;

            result = new byte[] { bcdType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    bcdType.encode(calendar.get(Calendar.MONTH) + 1)[0], bcdType.encode(dayOfWeek)[0],
                    bcdType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, SHORT)) {

            result = new byte[] { bcdType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    bcdType.encode(calendar.get(Calendar.MONTH) + 1)[0],
                    bcdType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, HEX)) {

            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;

            result = new byte[] { charType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    charType.encode(calendar.get(Calendar.MONTH) + 1)[0], charType.encode(dayOfWeek)[0],
                    charType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, HEX_SHORT)) {

            result = new byte[] { charType.encode(calendar.get(Calendar.DAY_OF_MONTH))[0],
                    charType.encode(calendar.get(Calendar.MONTH) + 1)[0],
                    charType.encode(calendar.get(Calendar.YEAR) % 100)[0] };

        } else if (StringUtils.equals(variant, DAYS)) {

            long millis = calendar.getTimeInMillis();

            calendar.clear();
            calendar.set(1900, 0, 1, 0, 0);
            long millis1900 = calendar.getTimeInMillis();

            BigDecimal days = new BigDecimal(millis - millis1900);
            days = days.divide(BigDecimal.valueOf(86400000), 0, RoundingMode.HALF_UP);

            result = wordType.encode(days);
        }
    }

    return result;
}

From source file:net.willwebberley.gowertides.ui.DaysActivity.java

private void populatePager(Calendar newToday, int daysToLoad) {
    fragments.clear();/*from   w w  w  .j a  va  2s.  co m*/
    Calendar startDay = (Calendar) newToday.clone();
    // Change the day to start the pager at (e.g., if 4, will start at day - DAYS_TO_STORE/4 and end at
    // 3*DAYS_TO_STORE/4.
    startDay.add(Calendar.DATE, -(daysToLoad / 4));
    for (int i = 0; i < DAYS_TO_STORE; i++) {
        Calendar newDay = (Calendar) startDay.clone();
        newDay.add(Calendar.DATE, i);

        Day day = Utilities.createDay(db, weather_db, newDay, locationKeys[locationIndex]);
        DayFragment dayFrag = new DayFragment(day, prefs, this);

        if (currentDay.getTimeInMillis() == newDay.getTimeInMillis()) {
            todayFragmentIndex = i;
        }
        fragments.add(dayFrag);
        if (newDay.getTimeInMillis() == lastDay.getTimeInMillis()) {
            break;
        }
    }
}

From source file:org.ambraproject.action.HomePageAction.java

/**
 * Populate the <b>recentArticles</b> (global) variable with random recent articles of
 * appropriate Article Type(s)./*from www . j  ava 2  s  .c  o  m*/
 * <ul>
 *   <li>The number of articles set into the <b>recentArticles</b>
 *     (global) variable determined by the
 *     <i>ambra.virtualJournals.CURRENT_JOURNAL_NAME.recentArticles.numArticlesToShow</i>
 *     configuration property
 *   </li>
 *   <li>The type of articles set into the <b>recentArticles</b> variable is determined by
 *     the list in the
 *   <i>ambra.virtualJournals.CURRENT_JOURNAL_NAME.recentArticles.typeUriListArticlesToShow</i>
 *     configuration property.
 *     If this property is not defined, then <b>all</b> types of articles are shown
 *   </li>
 *   <li>The initial definition of "recent" is the number of days (before today) indicated by
 *     the <i>ambra.virtualJournals.CURRENT_JOURNAL_NAME.recentArticles.numDaysInPast</i>
 *     configuration property.
 *     If not enough articles of the appropriate type are found in that span of time,
 *       then a new query is made for a somewhat longer duration.
 *   </li>
 * </ul>
 * The CURRENT_JOURNAL_NAME is acquired from the {@link BaseActionSupport#getCurrentJournal()}
 */
private void initRecentArticles() {
    String journalKey = getCurrentJournal();
    String rootKey = "ambra.virtualJournals." + journalKey + ".recentArticles";

    List<URI> typeUriArticlesToShow = getArticleTypesToShow(rootKey);

    numDaysInPast = configuration.getInteger(rootKey + ".numDaysInPast", 7);
    numArticlesToShow = configuration.getInteger(rootKey + ".numArticlesToShow", 5);

    //  This is the most recent midnight.  No need to futz about with exact dates.
    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);

    //  First query.  Just get the articles from "numDaysInPast" ago.
    Calendar endDate = (Calendar) startDate.clone();
    startDate.add(Calendar.DATE, -(numDaysInPast) + 1);

    BrowseParameters params = new BrowseParameters();
    params.setStartDate(startDate);
    params.setEndDate(endDate);
    params.setArticleTypes(typeUriArticlesToShow);
    params.setPageNum(0);
    params.setPageSize(numArticlesToShow * 100);
    params.setJournalKey(this.getCurrentJournal());

    BrowseResult results = browseService.getArticlesByDate(params);

    //Create a clone here so we're not modifying the object that is actually in the cache
    recentArticles = (ArrayList<SearchHit>) results.getArticles().clone();

    //  If not enough, then query for articles before "numDaysInPast" to make up the difference.
    if (recentArticles.size() < numArticlesToShow) {
        endDate = (Calendar) startDate.clone();
        endDate.add(Calendar.SECOND, -1); // So no overlap with the first query.
        startDate.add(Calendar.DATE, -(numDaysInPast) - 1); // One extra day to play it safe.

        params = new BrowseParameters();
        params.setStartDate(startDate);
        params.setEndDate(endDate);
        params.setArticleTypes(typeUriArticlesToShow);
        params.setPageNum(0);
        params.setPageSize(numArticlesToShow - recentArticles.size());
        params.setJournalKey(this.getCurrentJournal());

        recentArticles.addAll(browseService.getArticlesByDate(params).getArticles());
    }

    // Now choose a random selection of numArticlesToShow articles from the article pool.
    // Even if we do not have enough articles, this will still randomize their order.
    if (recentArticles.size() > 0) {
        Random randomNumberGenerator = new Random((new Date()).getTime()); // Seed: time = "now".
        ArrayList<SearchHit> recentArticlesTemp = new ArrayList<SearchHit>();
        while (recentArticlesTemp.size() < numArticlesToShow && recentArticles.size() > 0) {
            // Remove one random article from "recentArticles" and add it to "recentArticlesTemp".
            int randomNumber = randomNumberGenerator.nextInt(recentArticles.size());
            recentArticlesTemp.add(recentArticles.get(randomNumber));
            recentArticles.remove(randomNumber);
        }
        recentArticles = recentArticlesTemp;
    }
}

From source file:com.xpn.xwiki.plugin.chronopolys.Utils.java

/**
* Calculates the number of days between two calendar days 
* @param d1    The first date./*from ww w  .  j a  v a 2s.  c  o m*/
* @param d2    The second date.
* @return      The number of days between the two dates.  Zero is
*              returned if the dates are the same, one if the dates are
*              adjacent, etc.  
*              If Calendar types of d1 and d2
*              are different, the result may not be accurate.
*/
public int getDaysBetween(java.util.Calendar d1, java.util.Calendar d2) {
    boolean neg = false;
    if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
        java.util.Calendar swap = d1;
        d1 = d2;
        d2 = swap;
        neg = true;
    }
    int days = d2.get(java.util.Calendar.DAY_OF_YEAR) - d1.get(java.util.Calendar.DAY_OF_YEAR);
    int y2 = d2.get(java.util.Calendar.YEAR);
    if (d1.get(java.util.Calendar.YEAR) != y2) {
        d1 = (java.util.Calendar) d1.clone();
        do {
            days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
            d1.add(java.util.Calendar.YEAR, 1);
        } while (d1.get(java.util.Calendar.YEAR) != y2);
    }
    if (neg)
        return (-1) * days;
    return days;
}