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.alfresco.mobile.android.api.services.impl.onpremise.OnPremiseWorkflowServiceImpl.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
private PagingResult<Task> getTasks(String link, ListingContext listingContext) {
    List<Task> tasks = new ArrayList<Task>();
    Map<String, Object> json = new HashMap<String, Object>(0);
    int maxItems = -1;
    int size = 0;
    try {//from  www  . j a  va  2 s  .co m
        UrlBuilder url = new UrlBuilder(link);
        if (listingContext != null) {
            if (listingContext.getFilter() != null) {
                ListingFilter lf = listingContext.getFilter();

                // Assignee
                if (lf.hasFilterValue(FILTER_KEY_ASSIGNEE)) {
                    if (lf.getFilterValue(FILTER_KEY_ASSIGNEE) instanceof String) {
                        url.addParameter(OnPremiseConstant.AUTHORITY_VALUE,
                                lf.getFilterValue(FILTER_KEY_ASSIGNEE));
                    } else if (lf.getFilterValue(FILTER_KEY_ASSIGNEE) instanceof Integer) {
                        switch ((Integer) lf.getFilterValue(FILTER_KEY_ASSIGNEE)) {
                        case FILTER_ASSIGNEE_UNASSIGNED:
                            url.addParameter(OnPremiseConstant.AUTHORITY_VALUE, session.getPersonIdentifier());
                            url.addParameter(OnPremiseConstant.POOLEDTASKS_VALUE, true);
                            break;
                        case FILTER_ASSIGNEE_ME:
                            url.addParameter(OnPremiseConstant.AUTHORITY_VALUE, session.getPersonIdentifier());
                            url.addParameter(OnPremiseConstant.POOLEDTASKS_VALUE, false);
                            break;
                        case FILTER_ASSIGNEE_ALL:
                            url.addParameter(OnPremiseConstant.AUTHORITY_VALUE, session.getPersonIdentifier());
                            break;
                        case FILTER_NO_ASSIGNEE:
                            break;
                        default:
                            break;
                        }
                    }
                } else {
                    url.addParameter(OnPremiseConstant.AUTHORITY_VALUE, session.getPersonIdentifier());
                }

                if (lf.hasFilterValue(FILTER_KEY_PRIORITY)) {
                    url.addParameter(OnPremiseConstant.PRIORITY_VALUE, lf.getFilterValue(FILTER_KEY_PRIORITY));
                }

                if (lf.hasFilterValue(FILTER_KEY_STATUS)) {
                    switch ((Integer) lf.getFilterValue(FILTER_KEY_STATUS)) {
                    case FILTER_STATUS_COMPLETE:
                        url.addParameter(OnPremiseConstant.STATE_VALUE,
                                OnPremiseConstant.COMPLETED_UPPERCASE_VALUE);
                        break;
                    case FILTER_STATUS_ACTIVE:
                        url.addParameter(OnPremiseConstant.STATE_VALUE,
                                OnPremiseConstant.IN_PROGRESS_UPPERCASE_VALUE);
                        break;
                    case FILTER_STATUS_ANY:
                        url.addParameter(OnPremiseConstant.INCLUDETASKS_VALUE, "true");
                        break;
                    default:
                        break;
                    }
                }

                if (lf.hasFilterValue(FILTER_KEY_DUE)) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);
                    calendar.set(Calendar.MILLISECOND, 999);

                    switch ((Integer) lf.getFilterValue(FILTER_KEY_DUE)) {
                    case FILTER_DUE_TODAY:
                        url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar));

                        calendar.add(Calendar.DAY_OF_MONTH, -1);
                        url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar));
                        break;
                    case FILTER_DUE_TOMORROW:
                        url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar));

                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                        url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar));
                        break;
                    case FILTER_DUE_7DAYS:
                        url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar));

                        calendar.add(Calendar.DAY_OF_MONTH, 7);
                        url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar));
                        break;
                    case FILTER_DUE_OVERDUE:
                        calendar.add(Calendar.DAY_OF_MONTH, -1);
                        url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar));
                        break;
                    case FILTER_DUE_NODATE:
                        url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, "");
                        break;
                    default:
                        break;
                    }
                }
            }

            url.addParameter(OnPremiseConstant.MAX_ITEMS_VALUE, listingContext.getMaxItems());
            maxItems = listingContext.getMaxItems();
            url.addParameter(OnPremiseConstant.SKIP_COUNT_VALUE, listingContext.getSkipCount());
        } else {
            url.addParameter(OnPremiseConstant.STATE_VALUE, OnPremiseConstant.IN_PROGRESS_UPPERCASE_VALUE);
        }

        Log.d(TAG, url.toString());

        // send and parse
        Response resp = read(url, ErrorCodeRegistry.WORKFLOW_GENERIC);
        json = JsonUtils.parseObject(resp.getStream(), resp.getCharset());
        if (json != null) {
            List<Object> jo = null;
            if (json.get(OnPremiseConstant.DATA_VALUE) instanceof List) {
                jo = (List<Object>) json.get(OnPremiseConstant.DATA_VALUE);
            } else if (json.get(OnPremiseConstant.DATA_VALUE) instanceof Map) {
                Map<String, Object> jso = (Map<String, Object>) json.get(OnPremiseConstant.DATA_VALUE);
                jo = (List<Object>) jso.get(OnPremiseConstant.TASKS_VALUE);
            }

            size = jo.size();
            for (Object obj : jo) {
                tasks.add(TaskImpl.parseJson((Map<String, Object>) obj));
            }
        }
    } catch (Exception e) {
        convertException(e);
    }

    return new PagingResultImpl<Task>(tasks, maxItems != -1, size);

}

From source file:org.etudes.mneme.impl.AssessmentServiceImpl.java

/**
 * {@inheritDoc}//from   www  .j a v  a2s  .  c o  m
 */
public void applyBaseDateTx(String context, int days) {
    if (context == null)
        throw new IllegalArgumentException("applyBaseDateTx: context is null");
    if (days == 0)
        return;

    try {
        // security check
        securityService.secure(sessionManager.getCurrentSessionUserId(), MnemeService.MANAGE_PERMISSION,
                context);

        // do this the slow way (i.e. not all in SQL) to avoid the y2038 bug and assure proper gradebook integration
        // see Etudes Jira MN-1125

        // get all assessments
        List<Assessment> assessments = getContextAssessments(context, AssessmentsSort.odate_a, Boolean.FALSE);

        GregorianCalendar gc = new GregorianCalendar();

        // for each one, apply the base date change
        for (Assessment assessment : assessments) {
            if (assessment.getDates().getAcceptUntilDate() != null) {
                gc.setTime(assessment.getDates().getAcceptUntilDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setAcceptUntilDate(gc.getTime());
            }

            if (assessment.getDates().getDueDate() != null) {
                gc.setTime(assessment.getDates().getDueDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setDueDate(gc.getTime());
            }

            if (assessment.getDates().getOpenDate() != null) {
                gc.setTime(assessment.getDates().getOpenDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setOpenDate(gc.getTime());
            }

            if (assessment.getReview().getDate() != null) {
                gc.setTime(assessment.getReview().getDate());
                gc.add(Calendar.DATE, days);
                assessment.getReview().setDate(gc.getTime());
            }

            // save
            try {
                saveAssessment(assessment);
            } catch (AssessmentPermissionException e) {
                M_log.warn("applyBaseDateTx: " + assessment.getId() + " exception: " + e.toString());
            } catch (AssessmentPolicyException e) {
                M_log.warn("applyBaseDateTx: " + assessment.getId() + " exception: " + e.toString());
            }
        }
    } catch (AssessmentPermissionException e) {
        throw new RuntimeException("applyBaseDateTx: security check failed: " + e.toString());
    }
}

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

/**
 * To apply this scenario, we will modify the start time of the scenario to repeat to
 * be the selected event time. For example, if the repeat interval is one year (in milliseconds), 
 * and apply is called with a start time around 1992, then the child scenario is called
 * with a start time of 1977, 1978, to the end-time (present day or death being most common
 * for chronic diseases or the duration of the disease for acute diseases).
 * Since most repeat scenarios represent followup activity, the start date is often offset 
 * by some interval. Thus, with a startOffset of 12 (months), and the 
 * startDate were to be 1976, then the first "repeat" will be around 1977. 
 *///  www .ja v a2s  .c om
public boolean apply(GenMedical patient, Date startTime, Date endTime, RandomData rng) {
    GregorianCalendar clock = new GregorianCalendar();
    clock.setTime(startTime);
    boolean rslt = false;
    int count = -startOffset;
    //      TolvenLogger.info( getTitle() + " of " + getScenarioToRepeat().getTitle() + " Ranging from " + clock.getTime() + " to " + endTime, RepeatScenario.class); 
    while (true) {
        if (count++ >= MAX_REPEAT)
            throw new IllegalArgumentException("Maximum repeat for scenario " + getTitle());
        if (count > maxCount)
            break;
        // Now pick a random time around that clock setting unless this is the first instance or there is no deviation
        Date instanceTime;
        if (getDeviation() == 0.0 || count <= 0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // Needs to be before the end time, otherwise, we're done.
        if (instanceTime.after(endTime))
            break;
        // Now apply the instance (if we're past the startOffset)
        if (count > 0) {
            getScenarioToRepeat().apply(patient, instanceTime, endTime, rng);
        }
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
        rslt = true;
    }
    // If there's a future count, then we keep going by calling the futureScenario
    // Note: Logic is similar but not identical to above.
    for (int x = 0; x < getFutureCount(); x++) {
        Date instanceTime;
        if (getDeviation() == 0.0) {
            instanceTime = new Date(clock.getTimeInMillis());
        } else {
            instanceTime = new Date(((long) rng.nextGaussian(clock.getTimeInMillis(), getDeviationMs())));
        }
        // 
        // In the future, start and end time are the same.
        getFutureScenario().apply(patient, instanceTime, instanceTime, rng);
        // Reset the clock if requested
        if (resetClock)
            clock.setTime(instanceTime);
        // Advance the clock with no randomness
        clock.add(intervalType, intervalValue);
    }
    return rslt;
}

From source file:org.webical.test.web.component.DayViewPanelTest.java

public void testWithEvents() throws WebicalException {

    // Get the CalendarManager.
    MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock
            .getBean("calendarManager");
    Calendar calendar1 = mockCalendarManager.getCalendarById("1");

    // Add an EventManager for the test Events.
    MockEventManager mockEventManager = new MockEventManager();
    annotApplicationContextMock.putBean("eventManager", mockEventManager);

    final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek());

    GregorianCalendar cal = CalendarUtils.duplicateCalendar(currentDate);
    GregorianCalendar refcal = CalendarUtils.duplicateCalendar(currentDate);
    refcal.set(GregorianCalendar.HOUR_OF_DAY, 12);
    refcal.set(GregorianCalendar.MINUTE, 0);
    refcal.set(GregorianCalendar.SECOND, 0);

    // Create list with events for the manager
    final List<Event> events = new ArrayList<Event>();
    // Add a normal event
    Event event = new Event();
    event.setUid("e1");
    event.setCalendar(calendar1);/*from  w w  w.j a va 2s . co m*/
    event.setSummary("Normal Event Summary");
    event.setLocation("Normal Event Location");
    event.setDescription("Normal Event Description");
    event.setDtStart(refcal.getTime());
    event.setDtEnd(CalendarUtils.addHours(refcal.getTime(), 2));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a recurring event, starting yesterday, ending tommorrow
    event = new Event();
    event.setUid("e2");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Yesterday Summary");
    event.setLocation("Recurring Event Location");
    event.setDescription("Recurring Event Yesterday Description");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.DAY_OF_MONTH, 2);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event, new Recurrence(0, 1, cal.getTime()));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a recurring event, starting last month, ending next month
    event = new Event();
    event.setUid("e3");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Last Month Summary");
    event.setLocation("Recurring Event Location");
    event.setDescription("Recurring Event Last Month Description");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.MONTH, 2);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event, new Recurrence(0, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a (pseudo) all day event, starting today 00:00 hours, ending today 00:00 hours
    event = new Event();
    event.setUid("e4");
    event.setCalendar(calendar1);
    event.setSummary("Pseudo All Day Event");
    event.setLocation("All Day Event Location");
    event.setDescription("Starting yesterday midnight, ending today 00:00 hours");
    cal.setTime(refcal.getTime());
    cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
    cal.set(GregorianCalendar.MINUTE, 0);
    cal.set(GregorianCalendar.SECOND, 0);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Create the test page with a DayViewPanel
    wicketTester.startPage(new ITestPageSource() {
        private static final long serialVersionUID = 1L;

        public Page getTestPage() {
            return new PanelTestPage(new DayViewPanel(PanelTestPage.PANEL_MARKUP_ID, 1, currentDate) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onAction(IAction action) {
                    /* NOTHING TO DO */ }
            });
        }
    });

    // Basic assertions
    wicketTester.assertRenderedPage(PanelTestPage.class);
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, DayViewPanel.class);

    // Assert the heading label
    DateFormat dateFormat = new SimpleDateFormat("EEEE", getTestSession().getLocale());
    wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":dayLink",
            dateFormat.format(currentDate.getTime()));

    // Assert the number of events rendered
    String panelPath = PanelTestPage.PANEL_MARKUP_ID + ":eventItem";
    wicketTester.assertListView(panelPath, events);
}

From source file:eu.cloudscale.showcase.generate.GenerateHibernate.java

@Override
public void populateOrdersAndCC_XACTSTable() {
    GregorianCalendar cal;
    String[] credit_cards = { "VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS" };
    int num_card_types = 5;
    String[] ship_types = { "AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL" };
    int num_ship_types = 6;

    String[] status_types = { "PROCESSING", "SHIPPED", "PENDING", "DENIED" };
    int num_status_types = 4;

    // Order variables
    int O_C_ID;/*from  w  w  w .  j av a2  s.  c  o  m*/
    java.sql.Timestamp O_DATE;
    double O_SUB_TOTAL;
    double O_TAX;
    double O_TOTAL;
    String O_SHIP_TYPE;
    java.sql.Timestamp O_SHIP_DATE;
    int O_BILL_ADDR_ID, O_SHIP_ADDR_ID;
    String O_STATUS;

    String CX_TYPE;
    int CX_NUM;
    String CX_NAME;
    java.sql.Date CX_EXPIRY;
    String CX_AUTH_ID;
    int CX_CO_ID;

    System.out.println("Populating ORDERS, ORDER_LINES, CC_XACTS with " + NUM_ORDERS + " orders");

    System.out.print("Complete (in 10,000's): ");

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    for (int i = 1; i <= NUM_ORDERS; i++) {
        if (i % 1000 == 0) {
            session.flush();
            session.clear();

            System.out.print(i / 1000 + " ");
        }

        if (i % 10000 == 0) {
            System.out.println();
        }

        int num_items = getRandomInt(1, 5);

        cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 60));
        O_DATE = new java.sql.Timestamp(cal.getTime().getTime());
        O_SUB_TOTAL = (double) getRandomInt(1000, 999999) / 100;
        O_TAX = O_SUB_TOTAL * 0.0825;
        O_TOTAL = O_SUB_TOTAL + O_TAX + 3.00 + num_items;
        O_SHIP_TYPE = ship_types[getRandomInt(0, num_ship_types - 1)];
        cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 7));
        O_SHIP_DATE = new java.sql.Timestamp(cal.getTime().getTime());

        O_STATUS = status_types[getRandomInt(0, num_status_types - 1)];

        Orders order = new Orders();

        ICustomer customer = this.customers.get(getRandomInt(1, this.customers.size() - 1));
        IAddress billAddress = this.addresses.get(getRandomInt(1, this.addresses.size() - 1));
        IAddress shipAddress = this.addresses.get(getRandomInt(1, this.addresses.size() - 1));

        //         int OL_I_ID = getRandomInt( 1, NUM_ITEMS );
        //         IItem item = itemDao.findById( OL_I_ID );

        // Set parameter
        order.setCustomer(customer);
        order.setODate(new Date(O_DATE.getTime()));
        order.setOSubTotal(O_SUB_TOTAL);
        order.setOTax(O_TAX);
        order.setOTotal(O_TOTAL);
        order.setOShipType(O_SHIP_TYPE);
        order.setOShipDate(O_SHIP_DATE);
        order.setAddressByOBillAddrId(billAddress);
        order.setAddressByOShipAddrId(shipAddress);
        order.setOStatus(O_STATUS);
        order.setCcXactses(new HashSet<ICcXacts>());
        order.setOrderLines(new HashSet<IOrderLine>());

        session.save(order);

        for (int j = 1; j <= num_items; j++) {
            int OL_ID = j;
            int OL_O_ID = i;

            int OL_QTY = getRandomInt(1, 300);
            double OL_DISCOUNT = (double) getRandomInt(0, 30) / 100;
            String OL_COMMENTS = getRandomAString(20, 100);

            OrderLine orderLine = new OrderLine();
            orderLine.setItem(this.items.get(getRandomInt(1, this.items.size() - 1)));
            orderLine.setOlQty(OL_QTY);
            orderLine.setOlDiscount(OL_DISCOUNT);
            orderLine.setOlComment(OL_COMMENTS);
            orderLine.setOrders(order);

            session.save(orderLine);
            order.getOrderLines().add(orderLine);

        }

        CX_TYPE = credit_cards[getRandomInt(0, num_card_types - 1)];
        CX_NUM = getRandomNString(16);
        CX_NAME = getRandomAString(14, 30);
        cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_YEAR, getRandomInt(10, 730));
        CX_EXPIRY = new java.sql.Date(cal.getTime().getTime());
        CX_AUTH_ID = getRandomAString(15);

        CcXacts ccXacts = new CcXacts();

        ccXacts.setCountry(this.countries.get(getRandomInt(1, this.countries.size() - 1)));
        ccXacts.setOrders(order);
        ccXacts.setCxType(CX_TYPE);
        ccXacts.setCxNum(CX_NUM);
        ccXacts.setCxName(CX_NAME);
        ccXacts.setCxExpiry(CX_EXPIRY);
        ccXacts.setCxAuthId(CX_AUTH_ID);
        ccXacts.setCxXactAmt(O_TOTAL);
        ccXacts.setCxXactDate(O_SHIP_DATE);

        //         ccXacts.setOrders( order );

        order.getCcXactses().add(ccXacts);

        session.save(ccXacts);

    }

    tx.commit();
    session.close();

    System.out.println("");
}

From source file:eionet.util.Util.java

/**
 * A method for calculating time difference in MILLISECONDS, between a date-time specified in input parameters and the current
 * date-time. <BR>//from   w  w w. j  av a 2 s  .c o  m
 * This should be useful for calculating sleep time for code that has a certain schedule for execution.
 *
 * @param hour
 *            An integer from 0 to 23. If less than 0 or more than 23, then the closest next hour to current hour is taken.
 * @param date
 *            An integer from 1 to 31. If less than 1 or more than 31, then the closest next date to current date is taken.
 * @param month
 *            An integer from Calendar.JANUARY to Calendar.DECEMBER. If out of those bounds, the closest next month to current
 *            month is taken.
 * @param wday
 *            An integer from 1 to 7. If out of those bounds, the closest next weekday to weekday month is taken.
 * @param zone
 *            A String specifying the time-zone in which the calculations should be done. Please see Java documentation an
 *            allowable time-zones and formats.
 * @return Time difference in milliseconds.
 */
public static long timeDiff(int hour, int date, int month, int wday, String zone) {

    GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zone));
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    cal.setFirstDayOfWeek(Calendar.MONDAY);

    /*
     * here we force the hour to be one of the defualts if (hour < 0) hour = 0; if (hour > 23) hour = 23;
     */
    int cur_hour = cal.get(Calendar.HOUR);

    if (cal.get(Calendar.AM_PM) == Calendar.PM) {
        cur_hour = 12 + cur_hour;
    }

    // here we assume that every full hour is accepted
    /*
     * if (hour < 0 || hour > 23) { hour = cur_hour>=23 ? 0 : cur_hour + 1; }
     */

    if (wday >= 1 && wday <= 7) {

        int cur_wday = cal.get(Calendar.DAY_OF_WEEK);
        if (hour < 0 || hour > 23) {
            if (cur_wday != wday) {
                hour = 0;
            } else {
                hour = cur_hour >= 23 ? 0 : cur_hour + 1;
            }
        }

        int amount = wday - cur_wday;
        if (amount < 0) {
            amount = 7 + amount;
        }
        if (amount == 0 && cur_hour >= hour) {
            amount = 7;
        }
        cal.add(Calendar.DAY_OF_WEEK, amount);
    } else if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) { // do something about when every date is accepted
        if (date < 1) {
            date = 1;
        }
        if (date > 31) {
            date = 31;
        }
        int cur_month = cal.get(Calendar.MONTH);
        int amount = month - cur_month;
        if (amount < 0) {
            amount = 12 + amount;
        }
        if (amount == 0) {
            if (cal.get(Calendar.DATE) > date) {
                amount = 12;
            } else if (cal.get(Calendar.DATE) == date) {
                if (cur_hour >= hour) {
                    amount = 12;
                }
            }
        }
        // cal.set(Calendar.DATE, date);
        cal.add(Calendar.MONTH, amount);
        if (date > cal.getActualMaximum(Calendar.DATE)) {
            date = cal.getActualMaximum(Calendar.DATE);
        }
        cal.set(Calendar.DATE, date);
    } else if (date >= 1 && date <= 31) {
        int cur_date = cal.get(Calendar.DATE);
        if (cur_date > date) {
            cal.add(Calendar.MONTH, 1);
        } else if (cur_date == date) {
            if (cur_hour >= hour) {
                cal.add(Calendar.MONTH, 1);
            }
        }
        cal.set(Calendar.DATE, date);
    } else {
        if (hour < 0 || hour > 23) {
            hour = cur_hour >= 23 ? 0 : cur_hour + 1;
        }
        if (cur_hour >= hour) {
            cal.add(Calendar.DATE, 1);
        }
    }

    if (hour >= 12) {
        cal.set(Calendar.HOUR, hour - 12);
        cal.set(Calendar.AM_PM, Calendar.PM);
    } else {
        cal.set(Calendar.HOUR, hour);
        cal.set(Calendar.AM_PM, Calendar.AM);
    }

    Date nextDate = cal.getTime();
    Date currDate = new Date();

    long nextTime = cal.getTime().getTime();
    long currTime = (new Date()).getTime();

    return nextTime - currTime;
}

From source file:org.apache.unomi.persistence.elasticsearch.ElasticSearchPersistenceServiceImpl.java

public void start() throws Exception {

    loadPredefinedMappings(bundleContext, false);

    // on startup
    new InClassLoaderExecute<Object>() {
        public Object execute(Object... args) throws Exception {
            logger.info("Connecting to ElasticSearch persistence backend using cluster name " + clusterName
                    + " and index name " + indexName + "...");

            bulkProcessorName = System.getProperty(BULK_PROCESSOR_NAME, bulkProcessorName);
            bulkProcessorConcurrentRequests = System.getProperty(BULK_PROCESSOR_CONCURRENT_REQUESTS,
                    bulkProcessorConcurrentRequests);
            bulkProcessorBulkActions = System.getProperty(BULK_PROCESSOR_BULK_ACTIONS,
                    bulkProcessorBulkActions);
            bulkProcessorBulkSize = System.getProperty(BULK_PROCESSOR_BULK_SIZE, bulkProcessorBulkSize);
            bulkProcessorFlushInterval = System.getProperty(BULK_PROCESSOR_FLUSH_INTERVAL,
                    bulkProcessorFlushInterval);
            bulkProcessorBackoffPolicy = System.getProperty(BULK_PROCESSOR_BACKOFF_POLICY,
                    bulkProcessorBackoffPolicy);

            Settings transportSettings = Settings.builder().put(CLUSTER_NAME, clusterName).build();
            client = new PreBuiltTransportClient(transportSettings);
            for (String elasticSearchAddress : elasticSearchAddressList) {
                String[] elasticSearchAddressParts = elasticSearchAddress.split(":");
                String elasticSearchHostName = elasticSearchAddressParts[0];
                int elasticSearchPort = Integer.parseInt(elasticSearchAddressParts[1]);
                try {
                    client.addTransportAddress(new InetSocketTransportAddress(
                            InetAddress.getByName(elasticSearchHostName), elasticSearchPort));
                } catch (UnknownHostException e) {
                    String message = "Error resolving address " + elasticSearchAddress
                            + " ElasticSearch transport client not connected";
                    throw new Exception(message, e);
                }//w  w w .  j  a  va2  s  . c  om
            }

            // let's now check the versions of all the nodes in the cluster, to make sure they are as expected.
            try {
                NodesInfoResponse nodesInfoResponse = client.admin().cluster().prepareNodesInfo().all()
                        .execute().get();

                org.elasticsearch.Version minimalVersion = org.elasticsearch.Version
                        .fromString(minimalElasticSearchVersion);
                org.elasticsearch.Version maximalVersion = org.elasticsearch.Version
                        .fromString(maximalElasticSearchVersion);
                for (NodeInfo nodeInfo : nodesInfoResponse.getNodes()) {
                    org.elasticsearch.Version version = nodeInfo.getVersion();
                    if (version.before(minimalVersion) || version.equals(maximalVersion)
                            || version.after(maximalVersion)) {
                        throw new Exception(
                                "ElasticSearch version on node " + nodeInfo.getHostname() + " is not within ["
                                        + minimalVersion + "," + maximalVersion + "), aborting startup !");
                    }
                }
            } catch (InterruptedException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            } catch (ExecutionException e) {
                throw new Exception("Error checking ElasticSearch versions", e);
            }

            // @todo is there a better way to detect index existence than to wait for it to startup ?
            boolean indexExists = false;
            int tries = 0;

            while (!indexExists && tries < 20) {

                IndicesExistsResponse indicesExistsResponse = client.admin().indices().prepareExists(indexName)
                        .execute().actionGet();
                indexExists = indicesExistsResponse.isExists();
                tries++;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.error("Interrupted", e);
                }
            }
            if (!indexExists) {
                logger.info("{} index doesn't exist yet, creating it...", indexName);
                Map<String, String> indexMappings = new HashMap<String, String>();
                indexMappings.put("_default_", mappings.get("_default_"));
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    if (!itemsMonthlyIndexed.contains(entry.getKey())
                            && !indexNames.containsKey(entry.getKey())) {
                        indexMappings.put(entry.getKey(), entry.getValue());
                    }
                }

                internalCreateIndex(indexName, indexMappings);
            } else {
                logger.info("Found index {}, ElasticSearch started successfully.", indexName);
                for (Map.Entry<String, String> entry : mappings.entrySet()) {
                    createMapping(entry.getKey(), entry.getValue());
                }
            }

            client.admin().indices().preparePutTemplate(indexName + "_monthlyindex")
                    .setTemplate(indexName + "-*").setOrder(1)
                    .setSettings(Settings.builder()
                            .put(NUMBER_OF_SHARDS, Integer.parseInt(monthlyIndexNumberOfShards))
                            .put(NUMBER_OF_REPLICAS, Integer.parseInt(monthlyIndexNumberOfReplicas)).build())
                    .execute().actionGet();

            getMonthlyIndex(new Date(), true);

            if (client != null && bulkProcessor == null) {
                bulkProcessor = getBulkProcessor();
            }

            refreshExistingIndexNames();

            logger.info("Waiting for GREEN cluster status...");

            client.admin().cluster().prepareHealth().setWaitForGreenStatus().get();

            logger.info("Cluster status is GREEN");

            return true;
        }
    }.executeInClassLoader();

    bundleContext.addBundleListener(this);

    timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            GregorianCalendar gc = new GregorianCalendar();
            int thisMonth = gc.get(Calendar.MONTH);
            gc.add(Calendar.DAY_OF_MONTH, 1);
            if (gc.get(Calendar.MONTH) != thisMonth) {
                String monthlyIndex = getMonthlyIndex(gc.getTime(), true);
                existingIndexNames.add(monthlyIndex);
            }
        }
    }, 10000L, 24L * 60L * 60L * 1000L);

    // load predefined mappings and condition dispatchers of any bundles that were started before this one.
    for (Bundle existingBundle : bundleContext.getBundles()) {
        if (existingBundle.getBundleContext() != null) {
            loadPredefinedMappings(existingBundle.getBundleContext(), true);
        }
    }

    logger.info(this.getClass().getName() + " service started successfully.");
}

From source file:org.gluu.oxeleven.PKCS11RestServiceTest.java

@BeforeSuite
public void init() {
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.add(GregorianCalendar.MINUTE, 5);
    expirationTime = calendar.getTimeInMillis();
}

From source file:PVGraph.java

public java.util.List<PeriodData> getMonthData(int year, int month) {
    Statement stmt = null;/*ww  w . j  a va 2s.c o  m*/
    String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month
            + " and CurrentPower != 0 order by DateTime";
    Map<String, PeriodData> result = new HashMap<String, PeriodData>();
    GregorianCalendar gc = new GregorianCalendar();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String serial = rs.getString("serial");
            PeriodData pd = result.get(serial);
            if (pd == null) {
                pd = new PeriodData();
                pd.serial = serial;
                pd.inverter = rs.getString("inverter");
                pd.startTotalPower = rs.getDouble("ETotalToday");
                gc.setTime(rs.getTimestamp("DateTime"));
                gc.set(Calendar.DAY_OF_MONTH, 1);
                gc.add(Calendar.MONTH, 1);
                gc.add(Calendar.DAY_OF_MONTH, -1);
                pd.numPowers = gc.get(Calendar.DAY_OF_MONTH);
                result.put(serial, pd);
            }
            double power = rs.getDouble("ETotalToday");
            gc.setTime(rs.getTimestamp("DateTime"));
            pd.powers[gc.get(Calendar.DAY_OF_MONTH) - 1] = power;
            pd.endTotalPower = power;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<PeriodData>(result.values());
}

From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRBeanTest.java

private Date addToDate(Date start, int field, int amount) {

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(start);/* w w w . j a  v  a2  s .c  o  m*/
    cal.add(field, amount);
    return cal.getTime();

}