Example usage for java.util GregorianCalendar add

List of usage examples for java.util GregorianCalendar add

Introduction

In this page you can find the example usage for java.util GregorianCalendar add.

Prototype

@Override
public void add(int field, int amount) 

Source Link

Document

Adds the specified (signed) amount of time to the given calendar field, based on the calendar's rules.

Usage

From source file:uk.nhs.cfh.dsp.srth.demographics.person.utils.PatientUtilsServiceImpl.java

public Calendar getRandomDateInTimeRange(Calendar anchor, int yearUpperBound, int yearLowerBound,
        int monthUpperBound, int monthLowerBound, int dayUpperBound, int dayLowerBound) {

    int randomYear = (int) (Math.random() * (yearUpperBound - yearLowerBound)) + yearLowerBound;
    int randomMonth = (int) (Math.random() * (monthUpperBound - monthLowerBound)) + monthLowerBound;
    int randomDay = (int) (Math.random() * (dayUpperBound - dayLowerBound)) + dayLowerBound;

    // debugging output
    if (logger.isDebugEnabled()) {
        logger.debug("Value of anchor year: " + anchor.get(Calendar.YEAR));
        logger.debug("Value of anchor month: " + anchor.get(Calendar.MONTH));
        logger.debug("Value of anchor date: " + anchor.get(Calendar.DATE));
        logger.debug("Value of randomYear : " + randomYear);
        logger.debug("Value of randomMonth : " + randomMonth);
        logger.debug("Value of randomDay : " + randomDay);
    }//from   ww  w .  j av  a2s  .c  om

    // forward calendar by year and month
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(anchor.getTime());
    calendar.add(Calendar.YEAR, -randomYear);
    calendar.add(Calendar.MONTH, -randomMonth);
    calendar.add(Calendar.DATE, -randomDay);
    if (logger.isDebugEnabled()) {
        logger.debug("Value of calendar.get(year) : " + calendar.get(Calendar.YEAR));
    }
    return calendar;
}

From source file:op.tools.SYSCalendar.java

/**
 * Generates an ArrayList of Dates. Stepping through the day in 15 minutes steps like {"17:00","17:15"...}
 * Der verwendete Datentyp ist GregorianCalendar
 *///  w w  w  .ja v a 2 s .  c om
public static ArrayList<Date> getTimeList() {
    ArrayList list = new ArrayList();
    GregorianCalendar gc = today();
    for (int i = 1; i <= 96; i++) {
        list.add(new Date(gc.getTimeInMillis()));
        gc.add(GregorianCalendar.MINUTE, 15);
    }
    return list;
}

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

public void getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID,
        Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w w  w .  j av a  2 s  . c o  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag);

        int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS;
        try {
            transferExpirationDays = AppConfig.getConfiguration()
                    .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS);
            // For output
            nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
        } catch (ConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
        }

        String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID();
        org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken();
        transferToken.setTransferToken(transferKey);
        // For output
        opaqueToken.value = transferKey.getBytes();

        GregorianCalendar gc = new GregorianCalendar();
        gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays);

        transferToken.setExpirationDate(gc.getTime());

        try {
            DatatypeFactory df = DatatypeFactory.newInstance();
            // For output
            expirationTime.value = df.newXMLGregorianCalendar(gc);
        } catch (DatatypeConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
        }

        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key);
            transferToken.getTransferKeys().add(tokenKey);
        }

        em.persist(transferToken);

        tx.commit();

        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:uk.nhs.cfh.dsp.srth.demographics.person.utils.PatientUtilsServiceImpl.java

public Calendar getSensibleRandomDateInTimeRangeRelativeToPatient(Patient patient, int yearUpperBound,
        int yearLowerBound, int monthUpperBound, int monthLowerBound, int dayUpperBound, int dayLowerBound) {

    Calendar anchor = Calendar.getInstance();
    /*/*from   w  ww  .  j  a va  2s . co  m*/
       * use time now as anchor point and get a random sensible date
       */
    Calendar randomCal = getSensibleRandomDateInTimeRange(anchor, yearUpperBound, yearLowerBound,
            monthUpperBound, monthLowerBound, dayUpperBound, dayLowerBound);
    Date randomDate = randomCal.getTime();
    // we set time now to NOW - 1 day
    Date dob = patient.getDob().getTime();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(dob);
    // reset time by 1 day
    gc.add(Calendar.DATE, 1);
    dob = gc.getTime();
    while (randomDate.before(dob)) {
        randomCal = getSensibleRandomDateInTimeRange(anchor, yearUpperBound, yearLowerBound, monthUpperBound,
                monthLowerBound, dayUpperBound, dayLowerBound);
        // reset random date
        randomDate = randomCal.getTime();
    }

    return randomCal;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.group.AddBookingRoomViewParamsController.java

@Override
public Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
    Map map = new HashMap<String, Object>();

    int filterGroup = Integer.parseInt(request.getParameter("filterGroup"));
    String filterDate = request.getParameter("filterDate");
    if (filterDate.compareTo("") == 0)
        filterDate = null;/*  ww w  . j a v  a  2 s. c  o  m*/
    int repType = Integer.parseInt(request.getParameter("repType"));
    int repCount = Integer.parseInt(request.getParameter("repCount"));

    String date = request.getParameter("date");
    String startStr = request.getParameter("startTime");
    String endStr = request.getParameter("endTime");

    GregorianCalendar cal = BookingRoomUtils.getCalendar(startStr);
    boolean collisions = false;

    //reservations in not visible time period
    if (repCount > 0) {
        GregorianCalendar nextS = BookingRoomUtils.getCalendar(startStr);
        GregorianCalendar nextE = BookingRoomUtils.getCalendar(endStr);

        List<Reservation> coll = BookingRoomUtils.getCollisions(reservationDao, repCount, repType, nextS,
                nextE);

        map.put("collisionsInNext", coll);
        map.put("collisionsInNextCount", coll.size());
        if (coll.size() > 0)
            collisions = true;
    }

    //reservations in currently visible time period
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    GregorianCalendar weekStart = BookingRoomUtils.getCalendar(BookingRoomUtils.getDate(cal) + " 00:00:00");

    GregorianCalendar weekEnd = (GregorianCalendar) weekStart.clone();
    weekEnd.add(Calendar.DAY_OF_YEAR, 7);
    weekEnd.add(Calendar.SECOND, -1);

    map.put("reservations", reservationDao.getReservationsBetween(weekStart, weekEnd, filterDate, filterGroup));
    map.put("timerange", date + " " + BookingRoomUtils.getHoursAndMinutes(startStr) + " - "
            + BookingRoomUtils.getHoursAndMinutes(endStr));

    String displayed = String.format(
            messageSource.getMessage("bookRoom.displayed.week", null, RequestContextUtils.getLocale(request)),
            BookingRoomUtils.getDate(weekStart), BookingRoomUtils.getDate(weekEnd));

    boolean filtered = false;

    if (filterDate != null) {//filter of date
        filtered = true;
        displayed = messageSource.getMessage("bookRoom.displayed.day", null,
                RequestContextUtils.getLocale(request)) + " " + filterDate;
    }

    if (filterGroup > 0) {
        filtered = true;
        displayed += (filterDate == null ? "," : " and") + " "
                + messageSource.getMessage("bookRoom.displayed.group", null,
                        RequestContextUtils.getLocale(request))
                + " " + getResearchGroup(filterGroup).getTitle();
    }

    if (filtered) {//we must verify that there are no reservations in selected range
        GregorianCalendar start = BookingRoomUtils.getCalendar(startStr);
        GregorianCalendar end = BookingRoomUtils.getCalendar(endStr);
        List<Reservation> coll = reservationDao.getReservationsBetween(start, end);
        if (coll.size() > 0) {
            //if the collision exists
            collisions = true;
            map.put("collisions", coll);
            map.put("collisionsCount", coll.size());
        }
    }

    map.put("displayed", displayed);

    map.put("collisionsExist", (collisions) ? "1" : "0");

    /*
    -- JSP can get this from params object --
    map.put("repCount", repCount);
    map.put("repType", repType);
    map.put("group", group);
    map.put("date", date);*/
    map.put("startTime", BookingRoomUtils.getHoursAndMinutes(startStr).replaceAll(":", ""));
    map.put("endTime", BookingRoomUtils.getHoursAndMinutes(endStr).replaceAll(":", ""));
    map.put("loggedUser", personDao.getLoggedPerson());
    GroupMultiController.setPermissionToRequestGroupRole(map, personDao.getLoggedPerson());

    return map;
}

From source file:uk.nhs.cfh.dsp.srth.demographics.person.utils.PersonUtilsServiceImpl.java

/**
 * Gets the age years relative to reference point.
 *
 * @param anchorTime the anchor time/* w w w.  j ava 2 s . c om*/
 * @param testTime the test time
 *
 * @return the age years relative to reference point
 */
public synchronized int getAgeYearsRelativeToReferencePoint(Calendar anchorTime, Calendar testTime) {

    Date refDate = anchorTime.getTime();
    Date testDate = testTime.getTime();
    int ageYears = 0;
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(testDate);
    // lopp through years incrementing age if test time is before reference time
    while (testDate.before(refDate)) {
        // increment gc
        gc.add(Calendar.YEAR, 1);
        // reset test date
        testDate = gc.getTime();
        // increment age
        ageYears++;
    }

    return ageYears;
}

From source file:org.eurekastreams.server.persistence.TabGroupMapper.java

/**
 * Clean up deleted tabs here using the expired date set earlier. Currently
 * this is hard-coded to be at least 20 (configurable) minutes since the tab
 * was originally deleted, but could be much longer because it is dependent
 * on the next tab that is deleted. If one tab is deleted on Jan 1st and the
 * next tab is deleted on March 1st, the 1st tab will remain flagged as
 * deleted in the database until March 1st so we definitely need a full
 * timestamp for this object.//from  w ww.  ja va  2s .co  m
 */
private void cleanUpDeletedTabs() {
    GregorianCalendar expiredDateTime = new GregorianCalendar();
    expiredDateTime.add(Calendar.MINUTE, -undeleteTabWindowInMinutes);

    getEntityManager()
            .createQuery(
                    "delete from Gadget gd where gd.deleted = true " + "and gd.dateDeleted < :expiredTimestamp")
            .setParameter("expiredTimestamp", expiredDateTime.getTime()).executeUpdate();

    getEntityManager()
            .createQuery(
                    "delete from Tab de where de.deleted = true " + "and de.dateDeleted < :expiredTimestamp")
            .setParameter("expiredTimestamp", expiredDateTime.getTime()).executeUpdate();

    try {
        getEntityManager()
                .createQuery("delete from TabTemplate de where de.deleted = true "
                        + "and de.dateDeleted < :expiredTimestamp")
                .setParameter("expiredTimestamp", expiredDateTime.getTime()).executeUpdate();
    } catch (Exception e) {
        // This should never happen because a tab template is not marked as deleted unless
        // there are no reference to it by active tabs
        logger.debug("Unable to delete a tab template because there is still a tab that references it");
    }

}

From source file:cz.zcu.kiv.eegdatabase.logic.pdf.ReservationPDF.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {/*from   w  w w .j  a v  a2 s  .  c o  m*/
        if (request.getParameter("type").compareTo("single") == 0) {
            int id = Integer.parseInt(request.getParameter("reservationId"));
            Reservation reservation = reservationDao.getReservationById(id);

            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=reservation-" + id + ".pdf");

            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/"));
            document.add(utils.setHeader(document, "Reservation listing"));

            /*Paragraph paragraph = new Paragraph("Reservation #" + id, FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, BaseColor.BLACK));
            paragraph.setAlignment(Element.ALIGN_CENTER);
            paragraph.setSpacingBefore(10);
            paragraph.setSpacingAfter(10);
            document.add(paragraph);*/

            document.add(formatReservation(reservation));

            document.close();
            response.flushBuffer();

            return null;
        }

        if (request.getParameter("type").compareTo("range") == 0) {

            String date = request.getParameter("date") + " 00:00:00";
            GregorianCalendar rangeStart = BookingRoomUtils.getCalendar(date);
            int length = Integer.parseInt(request.getParameter("length"));

            GregorianCalendar rangeEnd = (GregorianCalendar) rangeStart.clone();
            rangeEnd.add(Calendar.DAY_OF_YEAR, length);

            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=reservations.pdf");

            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/"));
            document.add(utils.setHeader(document, "Reservations listing"));

            java.util.List<Reservation> reservations = reservationDao.getReservationsBetween(rangeStart,
                    rangeEnd, "", 0);

            int count = 0;
            for (Reservation reservation : reservations) {
                document.add(formatReservation(reservation));
                if (++count % 6 == 0) {
                    document.newPage();
                    document.add(utils.setHeader(document, "Reservations listing"));
                }
            }
            document.close();
            response.flushBuffer();

            return null;
        }

        return null;
    } catch (Exception e) {
        ModelAndView mav = new ModelAndView(getFormView());
        Map data = new HashMap<String, Object>();
        data.put("error", e.getMessage());
        mav.addAllObjects(data);
        return mav;
    }
}

From source file:edu.umm.radonc.ca_dash.controllers.D3PieChartController.java

public void onSelectTimePeriod() {
    endDate = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);/*from w ww . ja v  a 2  s  .  c o  m*/

    switch (interval) {
    case "1wk":
        gc.add(Calendar.DATE, -7);
        startDate = gc.getTime();
        break;
    case "1m":
        gc.add(Calendar.MONTH, -1);
        startDate = gc.getTime();
        break;
    case "3m":
        gc.add(Calendar.MONTH, -3);
        startDate = gc.getTime();
        break;
    case "6m":
        gc.add(Calendar.MONTH, -6);
        startDate = gc.getTime();
        break;
    case "1y":
        gc.add(Calendar.YEAR, -1);
        startDate = gc.getTime();
        break;
    case "2y":
        gc.add(Calendar.YEAR, -2);
        startDate = gc.getTime();
        break;
    case "3y":
        gc.add(Calendar.YEAR, -3);
        startDate = gc.getTime();
        break;
    case "Q1":
        gc.setTime(FiscalDate.getQuarter(1));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q2":
        gc.setTime(FiscalDate.getQuarter(2));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q3":
        gc.setTime(FiscalDate.getQuarter(3));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    case "Q4":
        gc.setTime(FiscalDate.getQuarter(4));
        startDate = gc.getTime();
        gc.add(Calendar.MONTH, 3);
        endDate = gc.getTime();
        break;
    }
}

From source file:uk.nhs.cfh.dsp.srth.demographics.person.utils.PatientUtilsServiceImpl.java

public Calendar getDateRelativeToPatientAge(Patient p, int ageYears, int ageMonths, int ageDays) {

    GregorianCalendar gc = new GregorianCalendar();
    // get dob of patient
    gc.setTime(p.getDob().getTime());//from  w  w  w. j a v a  2s .c o  m
    // forward time using given parameters
    gc.add(Calendar.YEAR, ageYears);
    gc.add(Calendar.MONTH, ageMonths);
    gc.add(Calendar.DATE, ageDays);

    return gc;
}