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.hyperic.hq.bizapp.server.session.EmailManagerImpl.java

private void scheduleJob(Integer platId) throws SchedulerException {
    // Create new job name with the appId
    String name = EmailFilterJob.class.getName() + platId + "Job";

    Scheduler scheduler = Bootstrap.getBean(Scheduler.class);

    synchronized (SCHEDULER_LOCK) {

        Trigger[] triggers = scheduler.getTriggersOfJob(name, JOB_GROUP);
        if (triggers.length == 0) {
            JobDetail jobDetail = new JobDetail(name, JOB_GROUP, EmailFilterJob.class);

            String appIdStr = platId.toString();

            jobDetail.getJobDataMap().put(EmailFilterJob.APP_ID, appIdStr);

            // XXX: Make this time configurable?
            GregorianCalendar next = new GregorianCalendar();
            next.add(GregorianCalendar.MINUTE, 5);
            SimpleTrigger t = new SimpleTrigger(name + "Trigger", JOB_GROUP, next.getTime());

            Date nextfire = scheduler.scheduleJob(jobDetail, t);
            log.debug("Will queue alerts for platform " + platId + " until " + nextfire);
        } else {/*from  w  w w . ja  v a 2  s.  com*/
            // Already scheduled, there will only be a single trigger.
            log.debug("Already queing alerts for platform " + platId + ", will fire at "
                    + triggers[0].getNextFireTime());
        }
    }
}

From source file:cz.zcu.kiv.eegdatabase.webservices.rest.reservation.ReservationServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w.  j a va  2 s  .  c  o m*/
 */
@Override
@Transactional(readOnly = true)
public ReservationDataList getToDate(String date) throws RestServiceException {
    GregorianCalendar calendarFrom = new GregorianCalendar();
    GregorianCalendar calendarTo = new GregorianCalendar();
    try {
        log.debug(sf.parse(date));
        calendarFrom.setTime(sf.parse(date));
        calendarTo.setTime(sf.parse(date));
        calendarTo.add(Calendar.DAY_OF_MONTH, 1);
        List<Reservation> reservations = reservationDao.getReservationsBetween(calendarFrom, calendarTo);
        List<ReservationData> data = new ArrayList<ReservationData>(reservations.size());

        for (Reservation r : reservations) {
            data.add(new ReservationData(r.getReservationId(), r.getResearchGroup().getTitle(),
                    r.getResearchGroup().getResearchGroupId(), r.getStartTime(), r.getEndTime(),
                    r.getPerson().getGivenname() + " " + r.getPerson().getSurname(), r.getPerson().getEmail(),
                    canRemoveReservation(r)));
        }
        return new ReservationDataList(data);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RestServiceException(e);
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.results.ReviewAction.java

/**
 * /*from www  .  j  a va 2s.c  o m*/
 * @param pForm le formulaire
 * @param pRequest la requte
 * @return les paramtres
 */
private Object[] getParams(ActionForm pForm, HttpServletRequest pRequest) {
    ActionErrors errors = new ActionErrors();
    Object[] paramIn = null;
    ParamReviewForm currentForm = (ParamReviewForm) pForm;
    int index = 0;
    int nbDays = currentForm.getNbDays();
    String tre = currentForm.getTre();
    String ruleId = currentForm.getRuleId();
    String componentId = currentForm.getComponentId();

    ComponentDTO comp = new ComponentDTO();
    comp.setID(Long.decode(componentId).longValue());
    Date date = null;
    // Conversion en une date
    if (nbDays > 0) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.add(Calendar.DATE, -nbDays);
        date = gc.getTime();
    }
    String treLabel = WebMessages.getString(pRequest, tre);
    if (ruleId.length() > 0) {
        paramIn = new Object[] { comp, tre, treLabel, date, Long.decode(ruleId) };
    } else {
        paramIn = new Object[] { comp, tre, treLabel, date, null };
    }
    return paramIn;
}

From source file:org.alfresco.provision.AWSService.java

public Metrics getMetrics(String instanceId, List<String> measureNames) {
    GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest();
    getMetricRequest.setNamespace("AWS/EC2");
    getMetricRequest.setPeriod(60);// w w w . j  a va 2  s  .  com
    List<String> stats = new LinkedList<>();
    stats.add("Average");
    getMetricRequest.setStatistics(stats);

    getMetricRequest.setNamespace("AWS/EC2");

    Dimension dimension = new Dimension();
    dimension.withName("InstanceId").withValue(instanceId);
    getMetricRequest.setDimensions(Arrays.asList(dimension));

    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND));
    getMetricRequest.setEndTime(calendar.getTime());
    calendar.add(GregorianCalendar.MINUTE, -10);
    getMetricRequest.setStartTime(calendar.getTime());

    Map<Long, Metrics> measureSets = new HashMap<>();
    for (String measureName : measureNames) {
        getMetricRequest.setMetricName(measureName);

        GetMetricStatisticsResult metricStatistics = cloudWatchClient.getMetricStatistics(getMetricRequest);
        List<Datapoint> datapoints = metricStatistics.getDatapoints();
        for (Datapoint point : datapoints) {
            Calendar cal = new GregorianCalendar();
            cal.setTime(point.getTimestamp());
            Metrics measureSet = measureSets.get(cal.getTimeInMillis());
            if (measureSet == null) {
                measureSet = new Metrics();
                measureSet.timestamp = cal;
                measureSets.put(cal.getTimeInMillis(), measureSet);
            }
            measureSet.setMetric(measureName, point.getAverage());
        }
    }

    List<Metrics> sortedMeasureSets = new ArrayList<>(measureSets.values());
    if (sortedMeasureSets.size() == 0) {
        return null;
    } else {
        Collections.sort(sortedMeasureSets);
        return sortedMeasureSets.get(sortedMeasureSets.size() - 1);
    }
}

From source file:org.squale.squalix.stats.ComputeStats.java

/**
 * @return la date courante moins le nombre de mois dfinis
 *///from  w w  w  .  ja  v a 2s  .  c o  m
private Date getBeginDate() {
    GregorianCalendar cal = new GregorianCalendar();
    long today = Calendar.getInstance().getTimeInMillis();
    cal.add(GregorianCalendar.MONTH, 0 - NB_MONTHS);
    return cal.getTime();
}

From source file:edu.lternet.pasta.portal.statistics.GrowthStats.java

private ArrayList<String> buildLabels(GregorianCalendar start, GregorianCalendar end, int scale) {

    ArrayList<String> labels = new ArrayList<String>();

    GregorianCalendar lower = (GregorianCalendar) start.clone();
    GregorianCalendar upper = new GregorianCalendar();
    GregorianCalendar split = new GregorianCalendar();

    while (lower.getTimeInMillis() <= end.getTimeInMillis()) {
        upper.setTime(lower.getTime());//  w  w  w .  j av  a2s.co  m
        upper.add(scale, 1);
        split.setTime(
                new Date(lower.getTimeInMillis() + (upper.getTimeInMillis() - lower.getTimeInMillis()) / 2));
        /*
        System.out.printf("%s-%s-%s%n", lower.getTime().toString(),
                   split.getTime().toString(),
                   upper.getTime().toString());
         */
        labels.add(getLabel(scale, split));
        lower.setTime(upper.getTime());
    }

    return labels;

}

From source file:RolloverFileOutputStream.java

public RolloverFileOutputStream(String filename, boolean append, int retainDays, TimeZone zone)
        throws IOException {
    super(null);//from  w ww  . ja  va 2s . c o m

    _fileBackupFormat.setTimeZone(zone);
    _fileDateFormat.setTimeZone(zone);

    if (filename != null) {
        filename = filename.trim();
        if (filename.length() == 0)
            filename = null;
    }
    if (filename == null)
        throw new IllegalArgumentException("Invalid filename");

    _filename = filename;
    _append = append;
    _retainDays = retainDays;
    setFile();

    synchronized (RolloverFileOutputStream.class) {
        if (__rollover == null)
            __rollover = new Timer();

        _rollTask = new RollTask();

        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);
        __rollover.scheduleAtFixedRate(_rollTask, midnight.getTime(), 1000L * 60 * 60 * 24);
    }
}

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

/**
 * Clean up deleted gadgets here using the expired date set earlier. Currently this is hard-coded to be at least 20
 * (configurable) minutes since the gadget was originally deleted, but could be much longer because it is dependent
 * on the next gadget that is deleted. If one gadget is deleted on Jan 1st and the next gadget is deleted on March
 * 1st, the 1st gadget will remain flagged as deleted in the database until March 1st so we definitely need a full
 * timestamp for this object.//www  .  ja v  a2s.c o m
 */
private void cleanUpDeletedGadgets() {
    GregorianCalendar expiredDateTime = new GregorianCalendar();
    expiredDateTime.add(Calendar.MINUTE, -undeleteGadgetWindowInMinutes);

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

From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (!GBApplication.getPrefs().getBoolean("send_sunrise_sunset", false)) {
        LOG.info("won't send sunrise and sunset events (disabled in preferences)");
        return;/*from ww  w  .  j av a  2  s.c  om*/
    }
    LOG.info("will resend sunrise and sunset events");

    final GregorianCalendar dateTimeTomorrow = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    dateTimeTomorrow.set(Calendar.HOUR, 0);
    dateTimeTomorrow.set(Calendar.MINUTE, 0);
    dateTimeTomorrow.set(Calendar.SECOND, 0);
    dateTimeTomorrow.set(Calendar.MILLISECOND, 0);
    dateTimeTomorrow.add(GregorianCalendar.DAY_OF_MONTH, 1);

    /*
     * rotate ids ud reuse the id from two days ago for tomorrow, this way we will have
     * sunrise /sunset for 3 days while sending only sunrise/sunset per day
     */
    byte id_tomorrow = (byte) ((dateTimeTomorrow.getTimeInMillis() / (1000L * 60L * 60L * 24L)) % 3);

    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNRISE, id_tomorrow);
    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNSET, id_tomorrow);

    Prefs prefs = GBApplication.getPrefs();

    float latitude = prefs.getFloat("location_latitude", 0);
    float longitude = prefs.getFloat("location_longitude", 0);
    LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude);

    if (ActivityCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && prefs.getBoolean("use_updated_location_if_available", false)) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        if (provider != null) {
            Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                latitude = (float) lastKnownLocation.getLatitude();
                longitude = (float) lastKnownLocation.getLongitude();
                LOG.info("got longitude/latitude from last known location: " + latitude + "/" + longitude);
            }
        }
    }
    GregorianCalendar[] sunriseTransitSetTomorrow = SPA.calculateSunriseTransitSet(dateTimeTomorrow, latitude,
            longitude, DeltaT.estimate(dateTimeTomorrow));

    CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
    calendarEventSpec.durationInSeconds = 0;
    calendarEventSpec.description = null;

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNRISE;
    calendarEventSpec.title = "Sunrise";
    if (sunriseTransitSetTomorrow[0] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[0].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNSET;
    calendarEventSpec.title = "Sunset";
    if (sunriseTransitSetTomorrow[2] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[2].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }
}

From source file:com.eryansky.common.utils.DateUtil.java

/**
 *  ?2009-08-01/*  ww  w  .j a va2  s  .c  o  m*/
 */
public static String addMonth(String strdate) {

    Date date = new Date(); // ??

    String dateresult = null; // 
    // ??
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    // ?
    GregorianCalendar gc = new GregorianCalendar();

    try {
        date = df.parse(strdate); // ?
    } catch (ParseException e) {
        e.printStackTrace();
    }

    gc.setTime(date); // gc?

    gc.add(2, 1); // 2?1?(,)
    // ?
    gc.set(gc.get(gc.YEAR), gc.get(gc.MONTH), gc.get(gc.DATE));
    // ?
    dateresult = df.format(gc.getTime());

    return dateresult;
}