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:nl.clockwork.mule.ebms.util.EbMSMessageUtils.java

public static MessageHeader createMessageHeader(CollaborationProtocolAgreement cpa, EbMSMessageContext context,
        String hostname) throws DatatypeConfigurationException {
    String uuid = UUID.getUUID();
    PartyInfo sendingPartyInfo = CPAUtils.getSendingPartyInfo(cpa, context.getFromRole(),
            context.getServiceType(), context.getService(), context.getAction());
    PartyInfo receivingPartyInfo = CPAUtils.getReceivingPartyInfo(cpa, context.getToRole(),
            context.getServiceType(), context.getService(), context.getAction());
    //PartyInfo receivingPartyInfo = CPAUtils.getOtherReceivingPartyInfo(cpa,context.getFromRole(),context.getServiceType(),context.getService(),context.getAction());

    MessageHeader messageHeader = new MessageHeader();

    messageHeader.setVersion(Constants.EBMS_VERSION);
    messageHeader.setMustUnderstand(true);

    messageHeader.setCPAId(cpa.getCpaid());
    messageHeader.setConversationId(context.getConversationId() != null ? context.getConversationId() : uuid);

    messageHeader.setFrom(new From());
    PartyId from = new PartyId();
    from.setType(sendingPartyInfo.getPartyId().get(0).getType());
    from.setValue(sendingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getFrom().getPartyId().add(from);
    messageHeader.getFrom().setRole(sendingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setTo(new To());
    PartyId to = new PartyId();
    to.setType(receivingPartyInfo.getPartyId().get(0).getType());
    to.setValue(receivingPartyInfo.getPartyId().get(0).getValue());
    messageHeader.getTo().getPartyId().add(to);
    messageHeader.getTo().setRole(receivingPartyInfo.getCollaborationRole().get(0).getRole().getName());

    messageHeader.setService(new Service());
    messageHeader.getService()//  w  w w .  jav a 2 s .  c  om
            .setType(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getType());
    messageHeader.getService().setValue(
            sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getService().getValue());
    messageHeader.setAction(sendingPartyInfo.getCollaborationRole().get(0).getServiceBinding().getCanSend()
            .get(0).getThisPartyActionBinding().getAction());

    messageHeader.setMessageData(new MessageData());
    messageHeader.getMessageData().setMessageId(uuid + "@" + hostname);
    messageHeader.getMessageData().setRefToMessageId(context.getRefToMessageId());
    messageHeader.getMessageData()
            .setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()));

    ReliableMessaging rm = CPAUtils.getReliableMessaging(cpa, messageHeader);
    if (rm != null) {
        GregorianCalendar timestamp = messageHeader.getMessageData().getTimestamp().toGregorianCalendar();
        Duration d = rm.getRetryInterval().multiply(rm.getRetries().add(new BigInteger("1")).intValue());
        d.addTo(timestamp);
        timestamp.add(Calendar.SECOND, 1);
        messageHeader.getMessageData()
                .setTimeToLive(DatatypeFactory.newInstance().newXMLGregorianCalendar(timestamp));
    }

    DeliveryChannel channel = CPAUtils.getDeliveryChannel(sendingPartyInfo.getCollaborationRole().get(0)
            .getServiceBinding().getCanSend().get(0).getThisPartyActionBinding());

    messageHeader.setDuplicateElimination(PerMessageCharacteristicsType.ALWAYS
            .equals(channel.getMessagingCharacteristics().getDuplicateElimination()) ? "" : null);

    return messageHeader;
}

From source file:oscar.MyDateFormat.java

public static java.sql.Date getSysDateEX(String pDate, int days) {
    if (pDate == null || "".equals(pDate))
        return null;
    if ("TODAY".equals(pDate.toUpperCase()))
        return new java.sql.Date(new Date().getTime());
    try {//from ww w  .j  a  v a2  s. c o  m
        char sep = '-';
        boolean bnosep = false;
        int idx = pDate.indexOf(sep);
        if (idx < 0) {
            sep = '/';
            idx = pDate.indexOf(sep);
        }
        bnosep = idx < 0;
        int day, month, year;
        if (bnosep) {
            year = Integer.parseInt(pDate.substring(0, 4));
            month = Integer.parseInt(pDate.substring(4, 6));
            day = Integer.parseInt(pDate.substring(6, 8));
        } else {
            year = Integer.parseInt(pDate.substring(0, idx));
            int idx1 = pDate.indexOf(sep, idx + 1);
            month = Integer.parseInt(pDate.substring(idx + 1, idx1));
            idx = idx1;
            idx1 = pDate.indexOf(' ');
            if (idx1 < 0)
                idx1 = pDate.length();
            day = Integer.parseInt(pDate.substring(idx + 1, idx1));
        }
        if (month > 0) {
            month = month - 1;
        }
        GregorianCalendar cal = new GregorianCalendar(year, month, day);
        cal.add(Calendar.DAY_OF_YEAR, days);
        return new java.sql.Date(cal.getTime().getTime());
    } catch (Exception e) {
        MiscUtils.getLogger().debug("Invalid Date - the input date is in wrong format or out of range");
        return null;
    }
}

From source file:msec.org.Tools.java

public static String generateFullDayChart(String filename, OneDayValue[] data, String title) {
    if (data[0].getValues().length != 1440) {
        return "data size invalid";
    }//from  www. j  ava 2  s .co m
    if (data.length > 1) {
        if (data[1].getValues() == null || data[1].getValues().length != 1440) {
            return "data 1 invalid";
        }
    }

    XYDataset xydataset = createDataset(data);
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "time", "", xydataset, true, true, true);

    try {
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();

        //
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
        dateaxis.setLabelFont(new Font("", Font.PLAIN, 16)); //
        dateaxis.setLabelPaint(ChartColor.gray);
        dateaxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        dateaxis.setTickLabelPaint(ChartColor.GRAY);

        GregorianCalendar endgc = (GregorianCalendar) gc.clone();
        endgc.add(GregorianCalendar.DATE, 1);
        dateaxis.setMaximumDate(endgc.getTime());

        dateaxis.setTickMarksVisible(true);
        dateaxis.setTickMarkInsideLength(5);
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.HOUR, 2));
        dateaxis.setVerticalTickLabels(true);
        dateaxis.setLabel("");

        //
        ValueAxis rangeAxis = xyplot.getRangeAxis();//?
        rangeAxis.setLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setLabelPaint(ChartColor.gray);
        rangeAxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setTickLabelPaint(ChartColor.gray);
        rangeAxis.setLowerBound(0);

        //
        jfreechart.getLegend().setItemFont(new Font("", Font.PLAIN, 12));
        jfreechart.getLegend().setItemPaint(ChartColor.gray);
        jfreechart.getLegend().setBorder(0, 0, 0, 0);//

        //
        jfreechart.getTitle().setFont(new Font("", Font.PLAIN, 18));//
        jfreechart.getTitle().setPaint(ChartColor.gray);

        //?
        xyplot.setRangeGridlinePaint(ChartColor.GRAY);
        xyplot.setBackgroundPaint(ChartColor.WHITE);
        xyplot.setOutlinePaint(null);//

        int w = 500;
        int h = 300;

        // ChartUtilities.saveChartAsPNG(new File(filename), jfreechart, w, h);
        ChartUtilities.saveChartAsJPEG(new File(filename), 0.8f, jfreechart, w, h);

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

From source file:msec.org.Tools.java

public static String generateDaysChart(String filename, ArrayList<OneDayValue> data, OneAttrDaysChart chart,
        String title, int duration) {
    if (data.size() == 0) {
        return "data size invalid";
    }/*from  www .  j a  va2 s.c  o  m*/

    int date = Integer.parseInt(data.get(0).getDate());
    GregorianCalendar startgc = new GregorianCalendar(date / 10000, date % 10000 / 100 - 1, date % 100);

    XYDataset xydataset = createDaysDataset(data, startgc, chart);
    JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "time", "", xydataset, true, true, true);

    try {
        XYPlot xyplot = (XYPlot) jfreechart.getPlot();

        //
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setDateFormatOverride(new SimpleDateFormat("MM/dd"));
        dateaxis.setLabelFont(new Font("", Font.PLAIN, 16)); //
        dateaxis.setLabelPaint(ChartColor.gray);
        dateaxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        dateaxis.setTickLabelPaint(ChartColor.GRAY);

        dateaxis.setMinimumDate(startgc.getTime());
        GregorianCalendar endgc = (GregorianCalendar) startgc.clone();
        endgc.add(GregorianCalendar.DATE, duration);
        dateaxis.setMaximumDate(endgc.getTime());

        dateaxis.setTickMarksVisible(true);
        dateaxis.setTickMarkInsideLength(5);
        dateaxis.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 1));
        dateaxis.setVerticalTickLabels(true);
        dateaxis.setLabel("");

        //
        ValueAxis rangeAxis = xyplot.getRangeAxis();//?
        rangeAxis.setLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setLabelPaint(ChartColor.gray);
        rangeAxis.setTickLabelFont(new Font("", Font.PLAIN, 16));
        rangeAxis.setTickLabelPaint(ChartColor.gray);
        rangeAxis.setLowerBound(0);

        //
        jfreechart.getLegend().setItemFont(new Font("", Font.PLAIN, 12));
        jfreechart.getLegend().setItemPaint(ChartColor.gray);
        jfreechart.getLegend().setBorder(0, 0, 0, 0);//

        //
        jfreechart.getTitle().setFont(new Font("", Font.PLAIN, 18));//
        jfreechart.getTitle().setPaint(ChartColor.gray);

        //?
        xyplot.setRangeGridlinePaint(ChartColor.GRAY);
        xyplot.setBackgroundPaint(ChartColor.WHITE);
        xyplot.setOutlinePaint(null);//

        int w = 500;
        int h = 300;

        // ChartUtilities.saveChartAsPNG(new File(filename), jfreechart, w, h);
        ChartUtilities.saveChartAsJPEG(new File(filename), 0.8f, jfreechart, w, h);

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}

From source file:org.nuclos.common2.DateUtils.java

private static void calc(GregorianCalendar result, CalcFunction cf, CalcPair cp) {
    switch (cf) {
    case ADD://from   w  w w .jav  a  2  s.  com
        result.add(cp.x, cp.y);
        break;
    case SUBTRACT:
        result.add(cp.x, cp.y * (-1));
        break;
    case SET:
        switch (cp.x) {
        case Calendar.YEAR:
            result.set(Calendar.DAY_OF_YEAR,
                    cp.y == Integer.MIN_VALUE ? result.getActualMinimum(Calendar.DAY_OF_YEAR)
                            : result.getActualMaximum(Calendar.DAY_OF_YEAR));
            break;
        case Calendar.MONTH:
            result.set(Calendar.DAY_OF_MONTH,
                    cp.y == Integer.MIN_VALUE ? result.getActualMinimum(Calendar.DAY_OF_MONTH)
                            : result.getActualMaximum(Calendar.DAY_OF_MONTH));
            break;
        case Calendar.WEEK_OF_YEAR:
            result.set(Calendar.DAY_OF_WEEK, cp.y == Integer.MIN_VALUE ? Calendar.MONDAY : Calendar.SUNDAY);
            break;
        }
        break;
    }
}

From source file:org.webical.ical.RecurrenceUtil.java

public static java.util.Date getLastOccurrenceDate(Event event) throws WebicalException {
    if (!(event != null && isRecurrent(event))) {
        throw new WebicalException("This event is not recurrent: " + event);
    }/*w  ww . j a v  a2  s  .c  o m*/

    Recurrence recurrence = getRecurrenceFromRecurrenceRuleSet(event.getrRule());
    if (recurrence != null) { // Check if the recurrence end date is set. Use this as last date value
        if (recurrence.getEndDay() != null) {
            return recurrence.getEndDay();
        }

        // Check for use of count to determine the end date
        if (recurrence.getCount() >= 1 && recurrence.getInterval() >= 1) {
            GregorianCalendar endDateCalendar = new GregorianCalendar();
            endDateCalendar.setTime(event.getDtStart());
            int amountToAdd = (recurrence.getCount() * recurrence.getInterval());
            endDateCalendar.add(getCalendarIdentifierForFrequency(recurrence.getFrequency()), amountToAdd);

            return endDateCalendar.getTime();
        }
    }
    return null;
}

From source file:org.webical.ical.RecurrenceUtil.java

public static java.util.Date getNextOccurrenceDate(Event event, java.util.Date occurrenceDate)
        throws WebicalException, ParseException {
    if (!(event != null && isRecurrent(event))) {
        throw new WebicalException("This event is not recurrent: " + event);
    }// ww w  .  j av  a 2  s  .  c o m

    Recurrence recurrence = getRecurrenceFromRecurrenceRuleSet(event.getrRule());
    if (recurrence != null) { // Check for use of count to determine the end date
        if (recurrence.getCount() > 0 && recurrence.getInterval() > 0) {
            GregorianCalendar endDateCalendar = new GregorianCalendar();

            endDateCalendar.setTime(event.getDtStart());
            int amountToAdd = (recurrence.getCount() * recurrence.getInterval());
            endDateCalendar.add(getCalendarIdentifierForFrequency(recurrence.getFrequency()), amountToAdd);

            if (isApplicableOnDate(event, endDateCalendar.getTime())) {
                return endDateCalendar.getTime();
            }
            return null;
        }
    }
    return null;
}

From source file:org.mifos.calendar.CalendarUtils.java

public static DateTime getFirstDayForMonthUsingWeekRankAndWeekday(final DateTime startDate,
        final int calendarWeekOfMonth, final int dayOfWeek) {

    /*/* w  ww .  jav  a2  s . co m*/
     * In Joda time MONDAY=1 and SUNDAY=7, so shift these to SUNDAY=1, SATURDAY=7 to match this class
     */
    int calendarDayOfWeek = (dayOfWeek % 7) + 1;

    final GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(startDate.toDate());

    DateTime scheduleDate = null;
    // if current weekday is after the weekday on which schedule has to
    // lie, move to next week
    if (gc.get(Calendar.DAY_OF_WEEK) > calendarDayOfWeek) {
        gc.add(Calendar.WEEK_OF_MONTH, 1);
    }
    // set the weekday on which schedule has to lie
    gc.set(Calendar.DAY_OF_WEEK, calendarDayOfWeek);
    // if week rank is First, Second, Third or Fourth, Set the
    // respective week.
    // if current week rank is after the weekrank on which schedule has
    // to lie, move to next month
    if (!RankOfDay.getRankOfDay(calendarWeekOfMonth).equals(RankOfDay.LAST)) {
        if (gc.get(Calendar.DAY_OF_WEEK_IN_MONTH) > calendarWeekOfMonth) {
            gc.add(GregorianCalendar.MONTH, 1);
            gc.set(GregorianCalendar.DATE, 1);
        }
        // set the weekrank on which schedule has to lie
        gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, calendarWeekOfMonth);
        scheduleDate = new DateTime(gc.getTime().getTime());
    } else {// scheduleData.getWeekRank()=Last
        int M1 = gc.get(GregorianCalendar.MONTH);
        // assumption: there are 5 weekdays in the month
        gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 5);
        int M2 = gc.get(GregorianCalendar.MONTH);
        // if assumption fails, it means there exists 4 weekdays in a
        // month, return last weekday date
        // if M1==M2, means there exists 5 weekdays otherwise 4 weekdays
        // in a month
        if (M1 != M2) {
            gc.set(GregorianCalendar.MONTH, gc.get(GregorianCalendar.MONTH) - 1);
            gc.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 4);
        }
        scheduleDate = new DateTime(gc.getTime().getTime());
    }

    return scheduleDate;
}

From source file:org.mifos.calendar.CalendarUtils.java

/**
 * Set the day of week according to given start day to the require weekday, i.e. so it matches the meeting week day.
 *
 * e.g. - If start date is Monday 9 June 2008 and meeting week day is Tuesday, then roll forward the date to Tuesday
 * 10 June 2008 - or if start date is Sunday 8 June 2008 and meeting week day is Saturday, then roll forward the
 * date to Saturday 14 June 2008 - or if start date is Tuesday 10 2008 June and meeting week day is Monday, then
 * roll forward the date to Monday 16 June 2008 - or if start date is Sunday 8 June 2008 and meeting week day is
 * Sunday, then keep the date as Sunday 8 June 2008 - or if start date is Saturday 7 June 2008 and meeting week day
 * is Sunday, then roll forward the date to Sunday 9 June 2008.
 *///  www.j  a va2 s. c om
public static DateTime getFirstDateForWeek(final DateTime startDate, final int dayOfWeek) {

    /*
     * In Joda time MONDAY=1 and SUNDAY=7, so shift these to SUNDAY=1, SATURDAY=7 to match this class
     */
    int calendarDayOfWeek = (dayOfWeek % 7) + 1;

    final GregorianCalendar firstDateForWeek = new GregorianCalendar();
    firstDateForWeek.setTime(startDate.toDate());

    int startDateWeekDay = firstDateForWeek.get(Calendar.DAY_OF_WEEK);
    int amountOfDaysToAdd = calendarDayOfWeek - startDateWeekDay;
    if (amountOfDaysToAdd < 0) {
        amountOfDaysToAdd += 7;
    }
    firstDateForWeek.add(Calendar.DAY_OF_WEEK, amountOfDaysToAdd);
    return new DateTime(firstDateForWeek.getTime());
}

From source file:TimeLib.java

/**
 * Get the number of time units between the two given timestamps.
 * @param t0 the first timestamp (as a long)
 * @param t1 the second timestamp (as a long)
 * @param field the time unit to use, one of the {@link java.util.Calendar}
 * fields, or one of the extended fields provided by this class
 * (MILLENIUM, CENTURY, or DECADE)./*from   w ww .j  a  v  a2s.  c  om*/
 * @return the number of time units between the two timestamps
 */
public static int getUnitsBetween(long t0, long t1, int field) {
    boolean negative = false;
    if (t1 < t0) {
        long tmp = t1;
        t1 = t0;
        t0 = tmp; // swap
        negative = true;
    }
    GregorianCalendar gc1 = new GregorianCalendar();
    GregorianCalendar gc2 = new GregorianCalendar();
    gc1.setTimeInMillis(t0);
    gc2.setTimeInMillis(t1);

    // add 2 units less than the estimate to 1st date,
    // then serially add units till we exceed 2nd date
    int est = estimateUnitsBetween(t0, t1, field);
    boolean multiYear = isMultiYear(field);
    if (multiYear) {
        gc1.add(Calendar.YEAR, -field * (est - 2));
        est = -field * est;
    } else {
        gc1.add(field, est - 2);
    }
    int f = multiYear ? Calendar.YEAR : field;
    int inc = multiYear ? -field : 1;
    for (int i = est - inc;; i += inc) {
        gc1.add(f, inc);
        if (gc1.after(gc2)) {
            return negative ? inc - i : i - inc;
        }
    }
}