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:org.springframework.integration.x.rollover.file.RolloverFileOutputStream.java

/**
 * @param filename/*from  w  ww . j  a v  a2s  .c  om*/
 *            The filename must include the string "yyyy_mm_dd", which is replaced with the actual date when
 *            creating and rolling over the file.
 * @param append
 *            If true, existing files will be appended to.
 * @param zone
 *            the timezone for the output
 * @param dateFormat
 *            The format for the date file substitution. The default is "yyyy_MM_dd".
 * @param rolloverStartTimeMs
 *            Defines the time in [ms] of the first file roll over process to start.
 * @param rolloverPeriodMs
 *            Defines the frequency (in ms) of the file roll over processes.
 * @throws IOException
 *             if unable to create output
 */
public RolloverFileOutputStream(String filename, boolean append, TimeZone zone, String dateFormat,
        long rolloverStartTimeMs, long rolloverPeriodMs, long maxRolledFileSize, String archivePrefix,
        boolean compressArchive, int bufferSize, FileCompressor fileCompressor) throws IOException {

    super(null);

    this.bufferSize = bufferSize;
    this.compressArchive = compressArchive;
    this.archivePrefix = archivePrefix;
    this.maxRolledFileSize = maxRolledFileSize;

    if (dateFormat == null) {
        dateFormat = ROLLOVER_FILE_DATE_FORMAT;
    }

    fileDateFormat = new SimpleDateFormat(dateFormat);

    if (StringUtils.isEmpty(filename)) {
        throw new IllegalArgumentException("Invalid filename");
    }

    filePath = filename.trim();
    fileDir = new File(new File(filename).getAbsolutePath()).getParentFile();

    if (fileDir != null && (!fileDir.isDirectory() || !fileDir.canWrite())) {
        throw new IOException("Cannot write into directory: " + fileDir);
    }

    appendToFile = append;
    setFile(true);

    synchronized (RolloverFileOutputStream.class) {

        if (rolloverTimer == null) {
            rolloverTimer = new Timer(RolloverFileOutputStream.class.getName(), true);
        }

        rollTask = new RollTask();

        Date startTime = null;
        if (rolloverStartTimeMs <= 0) {
            Calendar now = Calendar.getInstance();
            now.setTimeZone(zone);

            GregorianCalendar midnight = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH), 23, 0);
            midnight.setTimeZone(zone);
            midnight.add(Calendar.HOUR, 1);

            startTime = midnight.getTime();
        } else {
            startTime = new Date(rolloverStartTimeMs);
        }

        long period = (rolloverPeriodMs <= 0) ? 86400000 : rolloverPeriodMs;

        rolloverTimer.scheduleAtFixedRate(rollTask, startTime, period);
    }

    this.fileCompressor = fileCompressor;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations.FetchActivityOperation.java

private GregorianCalendar getLastSuccessfulSyncTime() {
    long timeStampMillis = GBApplication.getPrefs().getLong(getLastSyncTimeKey(), 0);
    if (timeStampMillis != 0) {
        GregorianCalendar calendar = BLETypeConversions.createCalendar();
        calendar.setTimeInMillis(timeStampMillis);
        return calendar;
    }/*  w ww .  ja  va2 s. c  o m*/
    GregorianCalendar calendar = BLETypeConversions.createCalendar();
    calendar.add(Calendar.DAY_OF_MONTH, -10);
    return calendar;
}

From source file:org.opencms.notification.CmsContentNotification.java

/**
 * Creates the mail to be sent to the responsible user.<p>
 * /*from   w ww . ja va  2s. c  o  m*/
 * @return the mail to be sent to the responsible user
 */
protected String generateHtmlMsg() {

    // set the messages
    m_messages = Messages.get().getBundle(getLocale());

    StringBuffer htmlMsg = new StringBuffer();
    htmlMsg.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
    htmlMsg.append("<tr><td colspan=\"5\"><br/>");

    GregorianCalendar tomorrow = new GregorianCalendar(TimeZone.getDefault(),
            CmsLocaleManager.getDefaultLocale());
    tomorrow.add(Calendar.DAY_OF_YEAR, 1);
    List outdatedResources = new ArrayList();
    List resourcesNextDay = new ArrayList();
    List resourcesNextWeek = new ArrayList();

    // split all resources into three lists: the resources that expire, will be released or get outdated
    // within the next 24h, within the next week and the resources unchanged since a long time
    Iterator notificationCauses = m_notificationCauses.iterator();
    while (notificationCauses.hasNext()) {
        CmsExtendedNotificationCause notificationCause = (CmsExtendedNotificationCause) notificationCauses
                .next();
        if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_OUTDATED) {
            outdatedResources.add(notificationCause);
        } else if (notificationCause.getDate().before(tomorrow.getTime())) {
            resourcesNextDay.add(notificationCause);
        } else {
            resourcesNextWeek.add(notificationCause);
        }
    }
    Collections.sort(resourcesNextDay);
    Collections.sort(resourcesNextWeek);
    Collections.sort(outdatedResources);
    appendResourceList(htmlMsg, resourcesNextDay, m_messages.key(Messages.GUI_WITHIN_NEXT_DAY_0));
    appendResourceList(htmlMsg, resourcesNextWeek, m_messages.key(Messages.GUI_WITHIN_NEXT_WEEK_0));
    appendResourceList(htmlMsg, outdatedResources, m_messages.key(Messages.GUI_FILES_NOT_UPDATED_1,
            String.valueOf(OpenCms.getSystemInfo().getNotificationTime())));

    htmlMsg.append("</td></tr></table>");
    String result = htmlMsg.toString();
    return result;
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from ww w  .  j av a 2 s  .c  o m*/
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }
    // check that
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        boolean finded = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                finded = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(finded);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

From source file:com.qut.middleware.saml2.SAML2Test.java

private XMLGregorianCalendar generateXMLCalendar(int offset) {
    SimpleTimeZone gmt;/*from  w w w.j  a  va2s .co  m*/
    GregorianCalendar calendar;
    XMLGregorianCalendar xmlCalendar;

    /* GMT timezone TODO: I am sure this isn't correct need to ensure we set GMT */
    // GMT or UTC ??
    gmt = new SimpleTimeZone(0, "UTC");
    calendar = new GregorianCalendar(gmt);
    calendar.add(Calendar.MILLISECOND, offset);
    xmlCalendar = new XMLGregorianCalendarImpl(calendar);

    return xmlCalendar;
}

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

@Override
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object comm,
        BindException bindException) throws Exception {
    try {/*from  ww w . ja  v  a 2s  .  c om*/
        BookRoomCommand command = (BookRoomCommand) comm;
        status = messageSource.getMessage("bookRoom.controllerMessages.status.fail", null,
                RequestContextUtils.getLocale(request));
        comment = messageSource.getMessage("bookRoom.controllerMessages.comment.error.unknown", null,
                RequestContextUtils.getLocale(request));

        Person user = personDao.getLoggedPerson();
        int group = command.getSelectedGroup();
        int repType = command.getRepType();
        int repCount = command.getRepCount();
        String startStr = BookingRoomUtils.getHoursAndMinutes(command.getStartTimeCal());
        String endStr = BookingRoomUtils.getHoursAndMinutes(command.getEndTimeCal());

        Reservation res = new Reservation();

        Timestamp createTime = new Timestamp(new GregorianCalendar().getTimeInMillis());
        res.setCreationTime(createTime);
        res.setStartTime(command.getStartTimeTimestamp());
        res.setEndTime(command.getEndTimeTimestamp());

        res.setPerson(user);

        //searching for ResearchGroup
        ResearchGroup grp = getResearchGroup(group);
        res.setResearchGroup(grp);

        log.debug("Reservation has been created: " + ((res == null) ? "false" : "true"));
        reservationDao.create(res);

        if (repCount > 0) {
            comment = messageSource.getMessage("bookRoom.controllerMessages.comment.booked.multiple.part1",
                    null, RequestContextUtils.getLocale(request));
            comment += command.getDate() + ", from " + startStr + " to " + endStr + "<br>\n";

            GregorianCalendar nextS = command.getStartTimeCal();
            GregorianCalendar nextE = command.getEndTimeCal();

            for (int i = 0; i < repCount; i++) {
                //shift of dates
                int add = BookingRoomUtils.getWeeksAddCount(repType, i);
                nextS.add(Calendar.WEEK_OF_YEAR, add);
                nextE.add(Calendar.WEEK_OF_YEAR, add);
                Reservation newReservation = new Reservation();
                newReservation.setCreationTime(createTime);
                newReservation.setStartTime(new Timestamp(nextS.getTimeInMillis()));
                newReservation.setEndTime(new Timestamp(nextE.getTimeInMillis()));
                newReservation.setPerson(user);
                newReservation.setResearchGroup(grp);
                reservationDao.create(newReservation);

                comment += BookingRoomUtils.getDate(nextS) + ", from "
                        + BookingRoomUtils.getHoursAndMinutes(nextS) + " to "
                        + BookingRoomUtils.getHoursAndMinutes(nextE) + "<br>\n";
            }

            comment += String.format(
                    messageSource.getMessage("bookRoom.controllerMessages.comment.booked.multiple.part2", null,
                            RequestContextUtils.getLocale(request)),
                    repCount + 1);//+1 because we need count "original" reservation!
        } else {
            comment = String
                    .format(messageSource.getMessage("bookRoom.controllerMessages.comment.booked.single", null,
                            RequestContextUtils.getLocale(request)), command.getDate(), startStr, endStr);
        }

        status = messageSource.getMessage("bookRoom.controllerMessages.status.ok", null,
                RequestContextUtils.getLocale(request));
    } catch (Exception e) {
        log.error("Exception: " + e.getMessage() + "\n" + e.getStackTrace()[0].getFileName() + " at line "
                + e.getStackTrace()[0].getLineNumber(), e);

        status = messageSource.getMessage("bookRoom.controllerMessages.status.fail", null,
                RequestContextUtils.getLocale(request));
        comment = messageSource.getMessage("bookRoom.controllerMessages.comment.error.exception", null,
                RequestContextUtils.getLocale(request)) + " " + e.getMessage();
    }

    log.debug("Returning MAV" + " with status=" + status + "&comment=" + comment);
    ModelAndView mav = new ModelAndView(getSuccessView()/* + "?status=" + status + "&comment=" + comment*/);

    return mav;
}

From source file:org.apache.fulcrum.security.spi.AbstractUserManager.java

/**
 * Utility method that sets the user's password expiry date.
 * @param user The user whose password is to be changed.
 *
 * @author richard.brooks/*from   w  w w .j a  v a  2  s.  co  m*/
 * Created on Jan 16, 2006
 */
private void setPasswordExpiry(User user) {
    Calendar date = Calendar.getInstance();
    GregorianCalendar passwordExpiry = new GregorianCalendar(date.get(Calendar.YEAR), date.get(Calendar.MONTH),
            date.get(Calendar.DAY_OF_MONTH));
    passwordExpiry.add(Calendar.DAY_OF_MONTH, getPasswordDurationDays());
    user.setPasswordExpiryDate(passwordExpiry.getTime());
}

From source file:com.esd.ps.LoginController.java

/**
 * ,//from  w  ww .  jav a 2  s  .c  o  m
 * @return
 */
@RequestMapping(value = "/moneyList", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> moneyListPost() {
    Map<String, Object> map = new HashMap<String, Object>();
    //
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    int week = cal.get(Calendar.DAY_OF_WEEK);
    //
    if (week == 7) {
        week = 0;
    }
    //logger.debug("week:{}",week);
    //
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // ()?
    GregorianCalendar gc = new GregorianCalendar();
    // ??
    gc.setTime(new Date());
    // ??
    gc.add(5, -week);
    // 
    String beginDate = sdf.format(gc.getTime());
    String endDate = sdf.format(new Date());
    SimpleDateFormat sdf1 = new SimpleDateFormat("MMdd");
    String beginDate1 = sdf1.format(gc.getTime());
    String endDate1 = sdf1.format(new Date());
    //logger.debug("beginDate:{},endDate:{}",beginDate,endDate);
    manager manager = managerService.selectByPrimaryKey(1);
    List<Map<String, Object>> monthList = salaryService.getMoneyList("", "", endDate);
    List<Map<String, Object>> weekList = salaryService.getMoneyList(beginDate, endDate, "");
    List<Map<String, Object>> totleList = salaryService.getMoneyList("", "", "");

    map.put("salary", manager.getSalary());
    map.put("monthList", monthList);
    map.put("weekList", weekList);
    map.put("totleList", totleList);
    map.put("weekDate", beginDate1 + "-" + endDate1);
    return map;
}

From source file:com.intel.xdk.cache.Cache.java

private void setCookie(String cookieName, String cookieValue, int expires, boolean setExpired) {
    //set value/* w w  w  . j  a v  a  2s  .  c  o m*/
    SharedPreferences settings = activity.getSharedPreferences(cookies, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(cookieName, cookieValue);
    editor.commit();
    //set expires
    settings = activity.getSharedPreferences(cookiesExpires, 0);
    editor = settings.edit();
    if (setExpired || expires >= 0) {
        GregorianCalendar now = new GregorianCalendar();
        now.add(Calendar.DATE, expires);
        editor.putString(cookieName, sdf.format(now.getTime()));
    } else {
        editor.putString(cookieName, DONOTEXPIRE);
    }
    editor.commit();
}

From source file:org.geoserver.wms.map.MockHttpClientConnectionManager.java

@Override
public ConnectionRequest requestConnection(HttpRoute arg0, Object arg1) {
    return new ConnectionRequest() {

        @Override/*from   www .  j  a  v  a 2s.  c om*/
        public boolean cancel() {
            return false;
        }

        @Override
        public HttpClientConnection get(long arg0, TimeUnit arg1)
                throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            connections++;
            return new HttpClientConnection() {

                @Override
                public void shutdown() throws IOException {
                }

                @Override
                public void setSocketTimeout(int arg0) {
                }

                @Override
                public boolean isStale() {
                    return false;
                }

                @Override
                public boolean isOpen() {
                    return true;
                }

                @Override
                public int getSocketTimeout() {
                    return 0;
                }

                @Override
                public HttpConnectionMetrics getMetrics() {
                    return null;
                }

                @Override
                public void close() throws IOException {
                }

                @Override
                public void sendRequestHeader(HttpRequest arg0) throws HttpException, IOException {
                }

                @Override
                public void sendRequestEntity(HttpEntityEnclosingRequest arg0)
                        throws HttpException, IOException {
                }

                @Override
                public HttpResponse receiveResponseHeader() throws HttpException, IOException {
                    return new HttpResponse() {

                        List<Header> headers = new ArrayList<Header>();

                        @Override
                        public void addHeader(Header arg0) {
                        }

                        @Override
                        public void addHeader(String arg0, String arg1) {
                        }

                        @Override
                        public boolean containsHeader(String arg0) {
                            return false;
                        }

                        @Override
                        public Header[] getAllHeaders() {
                            return headers.toArray(new Header[] {});
                        }

                        public Header getHeader(String header) {
                            if ("transfer-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("date".equalsIgnoreCase(header)) {

                                return new BasicHeader(header,
                                        dateFormat.format(new GregorianCalendar().getTime()));
                            }
                            if ("cache-control".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, enableCache ? "public" : "no-cache");
                            }
                            if ("content-length".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, response.length() + "");
                            }
                            if ("content-encoding".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "identity");
                            }
                            if ("age".equalsIgnoreCase(header)) {
                                return new BasicHeader(header, "0");
                            }
                            if ("expires".equalsIgnoreCase(header) && enableCache) {
                                GregorianCalendar expires = new GregorianCalendar();
                                expires.add(GregorianCalendar.MINUTE, 30);
                                return new BasicHeader(header, dateFormat.format(expires.getTime()));
                            }
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public Header getFirstHeader(String header) {
                            Header value = getHeader(header);
                            headers.add(value);
                            return value;
                        }

                        @Override
                        public Header[] getHeaders(String header) {

                            return new Header[] { getFirstHeader(header) };
                        }

                        @Override
                        public Header getLastHeader(String header) {
                            return new BasicHeader(header, "");
                        }

                        @Override
                        public HttpParams getParams() {
                            // TODO Auto-generated method stub
                            return null;
                        }

                        @Override
                        public ProtocolVersion getProtocolVersion() {
                            return HttpVersion.HTTP_1_1;
                        }

                        @Override
                        public HeaderIterator headerIterator() {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public HeaderIterator headerIterator(String header) {
                            return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock");
                        }

                        @Override
                        public void removeHeader(Header arg0) {
                        }

                        @Override
                        public void removeHeaders(String arg0) {
                        }

                        @Override
                        public void setHeader(Header arg0) {
                        }

                        @Override
                        public void setHeader(String arg0, String arg1) {
                        }

                        @Override
                        public void setHeaders(Header[] arg0) {
                        }

                        @Override
                        public void setParams(HttpParams arg0) {
                        }

                        @Override
                        public HttpEntity getEntity() {
                            BasicHttpEntity entity = new BasicHttpEntity();
                            entity.setContentLength(response.length());
                            entity.setContent(
                                    new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)));
                            return entity;
                        }

                        @Override
                        public Locale getLocale() {
                            return Locale.ENGLISH;
                        }

                        @Override
                        public StatusLine getStatusLine() {
                            return new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK");
                        }

                        @Override
                        public void setEntity(HttpEntity arg0) {
                        }

                        @Override
                        public void setLocale(Locale arg0) {
                        }

                        @Override
                        public void setReasonPhrase(String arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusCode(int arg0) throws IllegalStateException {
                        }

                        @Override
                        public void setStatusLine(StatusLine arg0) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1) {
                        }

                        @Override
                        public void setStatusLine(ProtocolVersion arg0, int arg1, String arg2) {
                        }
                    };
                }

                @Override
                public void receiveResponseEntity(HttpResponse arg0) throws HttpException, IOException {
                }

                @Override
                public boolean isResponseAvailable(int arg0) throws IOException {
                    return true;
                }

                @Override
                public void flush() throws IOException {
                }
            };
        }
    };
}