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.itracker.web.scheduler.tasks.ReminderNotification.java

/**
 * This method is called by the scheduler to send the reminder
 * notifications.  The arguments can be used to configure which issues
 * and projects are included in the notifications.  The args should
 * include as the first parameter the base url of the server including
 * the scheme, hostname, port, and context.  For example:
 * <br>/* w ww  .  j  ava2s.  com*/
 * http://localhost:8080/itracker
 * <br>
 * If no other arguments are supplied it sends reminders to all
 * owners/admins of unresolved issues in all projects that have not been
 * modified in 30 days.  The second element of the array can be a number
 * that represents the number of days to use to check the last modified
 * date.  The third optional element is a number that represents the project
 * id to limit the notifications to. A fourth optional argument is the severity
 * to send the notification for.
 *
 * @param args optional arguments to configure the notification messages
 */
public void performTask(String[] args) {
    final List<Issue> issues;
    final ConfigurationService configurationService = ServletContextUtils.getItrackerServices()
            .getConfigurationService();

    String baseURL = configurationService.getSystemBaseURL();
    int notificationDays = configurationService.getIntegerProperty("reminder_notification_days",
            DEFAULT_ISSUE_AGE);

    int projectId = -1;
    int severity = -1;

    // Process arguments.
    if (args != null) {
        if (args.length > 0 && args[0] != null) {
            baseURL = args[0];
        }

        if (null == baseURL) {
            baseURL = DEFAULT_BASE_URL;
        }
        if (args.length > 1) {
            try {
                notificationDays = Integer.parseInt(args[1]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid issue age specified in ReminderNotification task.");
            }
        }
        if (args.length > 2) {
            try {
                projectId = Integer.parseInt(args[2]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid projectId specified in ReminderNotification task.");
            }
        }
        if (args.length > 3) {
            try {
                severity = Integer.parseInt(args[3]);
            } catch (NumberFormatException nfe) {
                logger.debug("Invalid severity specified in ReminderNotification task.");
            }
        }
    }
    if (notificationDays < 1) {
        logger.info("Reminder notifications are disabled for project " + projectId);
        return;
    }
    logger.debug("Reminder notifications being sent for project " + projectId + " with issues over "
            + notificationDays + " days old with severity " + severity + ".  Base URL = " + baseURL);

    try {
        IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();
        NotificationService notificationService = ServletContextUtils.getItrackerServices()
                .getNotificationService();
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_MONTH, 0 - notificationDays);
        Date threshold = cal.getTime();

        if (projectId > 0) {
            issues = issueService.getIssuesByProjectId(projectId, IssueUtilities.STATUS_RESOLVED);
        } else {
            issues = issueService.getIssuesWithStatusLessThan(IssueUtilities.STATUS_RESOLVED);
        }
        if (issues != null && issues.size() > 0) {
            for (Issue issue : issues) {
                if (severity >= 0 && issue.getSeverity() != severity) {
                    continue;
                }
                if (issue.getLastModifiedDate() != null && issue.getLastModifiedDate().before(threshold)) {
                    List<Notification> notifications = notificationService.getPrimaryIssueNotifications(issue);
                    for (Notification notification : notifications) {
                        if (notification.getUser().getEmail() != null
                                && notification.getUser().getEmail().indexOf('@') >= 0) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Sending reminder notification for issue " + issue.getId() + " to "
                                        + notification.getUser() + " users.");
                            }
                            notificationService.sendReminder(issue, notification.getUser(), baseURL,
                                    notificationDays);

                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error sending reminder notifications. Message: ", e);
        throw new RuntimeException("failed to send reminder notifications.", e);
    }
}

From source file:edu.jhuapl.openessence.web.util.Filters.java

private Date muckDate(Date date, int prepull, String resolution, int calWeekStartDay) {
    GregorianCalendar x = new GregorianCalendar();
    x.setTime(date);//w  w  w. j  a va2 s .c  o  m
    if (resolution != null && resolution.equals("weekly")) {
        x.add(Calendar.DATE, (-7 * prepull));
        // make sure week starts on week start day defined
        // in message.properties or datasource groovy file
        while (x.get(Calendar.DAY_OF_WEEK) != calWeekStartDay) {
            x.add(Calendar.DATE, -1);
        }
    } else if (resolution != null && resolution.equals("monthly")) {
        x.set(Calendar.DAY_OF_MONTH, 1);
    } else if (resolution != null && resolution.equals("daily")) {
        x.add(Calendar.DATE, -prepull);
    }
    return x.getTime();
}

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

public D3PieChartController() {
    endDate = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(endDate);/*w  w w  . j  a va  2  s .  c  o m*/
    gc.add(Calendar.MONTH, -1);
    startDate = gc.getTime();
    interval = "1m";
    this.df = new SimpleDateFormat("MM/dd/YYYY");
    this.selectedFacility = new Long(-1);
    this.dstats = new SynchronizedDescriptiveStatistics();
    this.interval = "";
    selectedFilters = new ArrayList<>();
    jsonData = new JSONArray();
}

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private Date day(final int offset) {
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.add(GregorianCalendar.DAY_OF_MONTH, offset);
    return gregorianCalendar.getTime();
}

From source file:org.oscarehr.PMmodule.web.ManageConsent.java

public boolean displayAsSelectedExpiry(int months) {
    if (previousConsentToView == null)
        return (months == -1);
    else {/*from w w  w.  j ava  2s .c  o m*/
        if (previousConsentToView.getExpiry() == null)
            return (months == -1);
        else {
            GregorianCalendar cal1 = new GregorianCalendar();
            cal1.setTime(previousConsentToView.getCreatedDate());
            cal1.add(Calendar.MONTH, months);

            return (DateUtils.isSameDay(cal1.getTime(), previousConsentToView.getExpiry()));
        }
    }
}

From source file:org.tolven.gen.model.GenMedical.java

/**
* Return a time relative to now// www.j  a v  a  2 s  . co  m
*/
public Date monthsAgo(int months) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(getNow());
    cal.add(GregorianCalendar.MONTH, -months);
    return cal.getTime();
}

From source file:org.kuali.kfs.coa.batch.dataaccess.impl.AccountingPeriodFiscalYearMakerImpl.java

/**
 * Adds one year to the given date//  ww  w . j  a v a  2 s  . co m
 * 
 * @param inDate date to increment
 * @return Date incoming date plus one year
 */
protected java.sql.Date addYearToDate(Date inDate) {
    GregorianCalendar currentCalendarDate = new GregorianCalendar();
    currentCalendarDate.clear();

    currentCalendarDate.setTimeInMillis(inDate.getTime());
    currentCalendarDate.add(GregorianCalendar.YEAR, 1);

    return new Date(currentCalendarDate.getTimeInMillis());
}

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

public Calendar getRandomDateInTimeRangeInFuture(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;

    // forward calendar by year and month
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(anchor.getTime());/*from   ww  w. j  av  a  2  s.  c o  m*/
    calendar.add(Calendar.YEAR, randomYear);
    calendar.add(Calendar.MONTH, randomMonth);
    calendar.add(Calendar.DATE, randomDay);
    logger.debug("Value of calendar.get(year) : " + calendar.get(Calendar.YEAR));

    return calendar;
}

From source file:com.jpeterson.littles3.bo.S3Authenticator.java

/**
 * Authenticate the request using the prescribed Amazon S3 authentication
 * mechanisms./*from  ww w.j av  a 2  s.  c o m*/
 * 
 * @param req
 *            The original HTTP request.
 * @param s3Request
 *            The S3 specific information for authenticating the request.
 * @return The authenticated <code>CanonicalUser</code> making the request.
 * @throws RequestTimeTooSkewedException
 *             Thrown if the request timestamp is outside of the allotted
 *             timeframe.
 */
public CanonicalUser authenticate(HttpServletRequest req, S3ObjectRequest s3Request)
        throws AuthenticatorException {
    // check to see if anonymous request
    String authorization = req.getHeader(HEADER_AUTHORIZATION);

    if (authorization == null) {
        return new CanonicalUser(CanonicalUser.ID_ANONYMOUS);
    }

    // attempting to be authenticated request

    if (false) {
        // check timestamp of request
        Date timestamp = s3Request.getTimestamp();
        if (timestamp == null) {
            throw new RequestTimeTooSkewedException("No timestamp provided");
        }

        GregorianCalendar calendar = new GregorianCalendar();
        Date now = calendar.getTime();
        calendar.add(Calendar.MINUTE, 15);
        Date maximumDate = calendar.getTime();
        calendar.add(Calendar.MINUTE, -30);
        Date minimumDate = calendar.getTime();

        if (timestamp.before(minimumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too old. System time: " + now);
        }

        if (timestamp.after(maximumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too new. System time: " + now);
        }
    }

    // authenticate request
    String[] fields = authorization.split(" ");

    if (fields.length != 2) {
        throw new InvalidSecurityException("Unsupported authorization format");
    }

    if (!fields[0].equals(AUTHORIZATION_TYPE)) {
        throw new InvalidSecurityException("Unsupported authorization type: " + fields[0]);
    }

    String[] keys = fields[1].split(":");

    if (keys.length != 2) {
        throw new InvalidSecurityException("Invalid AWSAccesskeyId:Signature");
    }

    String accessKeyId = keys[0];
    String signature = keys[1];
    String secretAccessKey = userDirectory.getAwsSecretAccessKey(accessKeyId);
    String calculatedSignature;

    try {
        SecretKey key = new SecretKeySpec(secretAccessKey.getBytes(), "HmacSHA1");
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(key);
        m.update(s3Request.getStringToSign().getBytes());
        byte[] mac = m.doFinal();
        calculatedSignature = new String(Base64.encodeBase64(mac));
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidSecurityException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidSecurityException(e);
    }

    System.out.println("-----------------");
    System.out.println("signature: " + signature);
    System.out.println("calculatedSignature: " + calculatedSignature);
    System.out.println("-----------------");

    if (calculatedSignature.equals(signature)) {
        // authenticated!
        return userDirectory.getCanonicalUser(secretAccessKey);
    } else {
        throw new SignatureDoesNotMatchException("Provided signature doesn't match calculated value");
    }
}

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

public Patient createRandomPatient(int minAge) {

    GregorianCalendar gc = new GregorianCalendar(1900, 0, 1);
    long centuryStart = gc.getTimeInMillis();
    // rewind time to now - 1
    GregorianCalendar gc2 = new GregorianCalendar();
    gc2.setTime(Calendar.getInstance().getTime());
    gc2.add(Calendar.YEAR, -minAge);
    long todayMinusMinYears = gc2.getTimeInMillis();

    // use a random value to generate values between century start and today
    long randomTime = (long) (Math.random() * (todayMinusMinYears - centuryStart)) + centuryStart;
    // use random time to set calendar
    gc.setTimeInMillis(randomTime);/* ww w  .j a  v  a2s  .co m*/

    // create and return patient with dob as random time
    return createRandomPatient(gc);
}