Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:org.kuali.mobility.events.controllers.CalendarController.java

@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(HttpServletRequest request, Model uiModel, @RequestParam(required = false) String date) {
    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Calendar selectedDate = Calendar.getInstance();
    try {/*from   w w w . ja  v a 2 s .com*/
        if (date != null) {
            selectedDate.setTime(sdf.parse(date));
        }
    } catch (ParseException e) {

    }
    try {
        Calendar endDate = (Calendar) selectedDate.clone();
        Calendar previousDate = (Calendar) selectedDate.clone();
        Filter filter = (Filter) request.getSession().getAttribute("calendar.event.filterId");
        ListViewEvents listViewEvents = calendarEventOAuthService.retrieveViewEventsList(user.getUserId(),
                selectedDate.getTime(), filter != null ? filter.getFilterId() : null);

        Calendar currentEndDate = (Calendar) selectedDate.clone();
        currentEndDate.add(Calendar.DATE, listViewEvents.getAppData().getListViewFutureDaysLimit());
        endDate.add(Calendar.DATE, listViewEvents.getAppData().getListViewFutureDaysLimit() * 2);
        previousDate.add(Calendar.DATE, -listViewEvents.getAppData().getListViewFutureDaysLimit());

        SimpleDateFormat my = new SimpleDateFormat("yyyyMM");

        uiModel.addAttribute("selectedDate", sdf.format(selectedDate.getTime()));
        uiModel.addAttribute("monthSelectedDate", my.format(selectedDate.getTime()));
        uiModel.addAttribute("beginDate", sdf.format(selectedDate.getTime()));
        uiModel.addAttribute("endDate", sdf.format(endDate.getTime()));
        uiModel.addAttribute("currentEndDate", sdf.format(currentEndDate.getTime()));
        uiModel.addAttribute("previousDate", sdf.format(previousDate.getTime()));
        uiModel.addAttribute("days", listViewEvents.getAppData().getListViewFutureDaysLimit());
        uiModel.addAttribute("viewData", listViewEvents.getViewData());
        uiModel.addAttribute("appData", listViewEvents.getAppData());
        uiModel.addAttribute("events", listViewEvents.getEvents());
        uiModel.addAttribute("filter", filter);
    } catch (PageLevelException pageLevelException) {
        uiModel.addAttribute("message", pageLevelException.getMessage());
        return "calendar/message";
    }
    return "calendar/list";
}

From source file:org.projectforge.common.DateHolder.java

/** Clones calendar. */
public DateHolder(final Calendar cal) {
    this.calendar = (Calendar) cal.clone();
}

From source file:it.govpay.web.console.pagamenti.service.DistintaService.java

private void impostaDate(DistintaSearchForm form, DistintaFilter filtro) {
    SelectList<SelectItem> dataPeriodo = form.getDataPeriodo();
    DateTime data = form.getData();//  w w w  .  j  a va 2s .  c  o  m

    Date dataInizio = data.getValue();
    Date dataFine = data.getValue2();

    String periodo = dataPeriodo.getValue() != null ? dataPeriodo.getValue().getValue()
            : DistintaSearchForm.DATA_PERIODO_ULTIMA_SETTIMANA;

    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 23);
    today.set(Calendar.MINUTE, 59);
    today.clear(Calendar.SECOND);
    today.clear(Calendar.MILLISECOND);

    //ultima settimana
    if (DistintaSearchForm.DATA_PERIODO_ULTIMA_SETTIMANA.equals(periodo)) {
        Calendar lastWeek = (Calendar) today.clone();
        Calendar c = Calendar.getInstance();
        dataFine = c.getTime();
        lastWeek.set(Calendar.HOUR_OF_DAY, 0);
        lastWeek.set(Calendar.MINUTE, 0);
        lastWeek.add(Calendar.DATE, -7);
        dataInizio = lastWeek.getTime();

    } else if (DistintaSearchForm.DATA_PERIODO_ULTIMO_MESE.equals(periodo)) {
        Calendar lastMonth = (Calendar) today.clone();

        // prendo la data corrente
        dataFine = Calendar.getInstance().getTime();

        // la data inizio rimane uguale sia per giornaliero che per orario
        lastMonth.set(Calendar.HOUR_OF_DAY, 0);
        lastMonth.set(Calendar.MINUTE, 0);
        lastMonth.add(Calendar.DATE, -30);
        dataInizio = lastMonth.getTime();

    } else if (DistintaSearchForm.DATA_PERIODO_ULTIMI_TRE_MESI.equals(periodo)) {
        Calendar lastyear = (Calendar) today.clone();

        dataFine = Calendar.getInstance().getTime();

        lastyear.set(Calendar.HOUR_OF_DAY, 0);
        lastyear.set(Calendar.MINUTE, 0);
        lastyear.add(Calendar.DATE, -90);
        dataInizio = lastyear.getTime();

    } else {
        // personalizzato
        dataInizio = data.getValue();
        dataFine = data.getValue2();
    }

    if (dataInizio != null) {
        log.debug("Data inizio[" + dataInizio + "]");
        filtro.setDataInizio(dataInizio);
    }

    if (dataFine != null) {
        log.debug("Data Fine[" + dataFine + "]");
        filtro.setDataFine(dataFine);
    }
}

From source file:org.projectforge.common.DateHolder.java

/** Clones the calendar. */
public DateHolder setCalendar(final Calendar cal) {
    this.calendar = (Calendar) cal.clone();
    ensurePrecision();//from www.  j a  v  a 2 s  .  c  om
    return this;
}

From source file:org.apache.stratos.usage.api.TenantUsageRetriever.java

public TenantUsage getTenantUsage(int tenantId, String yearMonth) throws Exception {
    //get the domain name
    TenantManager tenantManger = Util.getRealmService().getTenantManager();
    String domain = tenantManger.getDomain(tenantId);
    TenantUsage tenantUsage = new TenantUsage(tenantId, domain);

    //Get the startDate, endDate from yearMonth String
    Date date = CommonUtil.getDateFromMonthString(yearMonth);
    Calendar startDate = Calendar.getInstance();
    startDate.setTime(date);//from  w w  w .j a v  a  2s  .co m
    Calendar endDate = (Calendar) startDate.clone();
    endDate.add(Calendar.MONTH, 1);

    //Calculate whether the yearMonth fits to current month; if the current date is less than
    // endDate, then we treat it as current month
    boolean isCurrentMonth = (Calendar.getInstance().compareTo(endDate) <= 0);

    //get the data capacity
    TenantDataCapacity capacity;
    try {
        capacity = getDataCapacity(tenantId, startDate, endDate, isCurrentMonth);
    } catch (Exception e) {
        String msg = "Error in getting data capacity from metering service.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
    tenantUsage.setRegistryCapacity(capacity);

    //get the service request statistics
    RequestStatistics[] reqStats = null;
    try {
        reqStats = getRequestStatistics(tenantId, startDate, endDate, isCurrentMonth);
    } catch (Exception e) {
        String msg = "Error in getting request statistics from metering service.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
    tenantUsage.setRequestStatistics(reqStats);

    //Calculate total Request statistics
    RequestStatistics totalReqStat = new RequestStatistics(TOTAL_LABEL);
    long totalReq = 0;
    long totalRes = 0;
    long totalFault = 0;
    if (reqStats != null) {
        for (RequestStatistics stat : reqStats) {
            totalReq += stat.getRequestCount();
            totalRes += stat.getResponseCount();
            totalFault += stat.getFaultCount();
        }
        totalReqStat.setRequestCount(totalReq);
        totalReqStat.setResponseCount(totalRes);
        totalReqStat.setFaultCount(totalFault);
    }
    tenantUsage.setTotalRequestStatistics(totalReqStat);

    //get Bandwidth statistics
    BandwidthStatistics[][] bwStats = null;
    try {
        bwStats = getBandwidthStatistics(tenantId, startDate, endDate, isCurrentMonth);
    } catch (Exception e) {
        String msg = "Error in getting bandwidth statistics from metering service.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
    tenantUsage.setRegistryBandwidthStatistics(bwStats[REG_BANDWIDTH_INDEX]);
    tenantUsage.setServiceBandwidthStatistics(bwStats[SVC_BANDWIDTH_INDEX]);
    tenantUsage.setWebappBandwidthStatistics(bwStats[WEBAPP_BANDWIDTH_INDEX]);

    //get the total bandwidths
    int index = 0;
    for (BandwidthStatistics[] bwArray : bwStats) {
        long incomingBandwidth = 0;
        long outgoingBandwidth = 0;
        for (BandwidthStatistics bandwidth : bwArray) {
            incomingBandwidth += bandwidth.getIncomingBandwidth();
            outgoingBandwidth += bandwidth.getOutgoingBandwidth();
        }
        BandwidthStatistics total = new BandwidthStatistics(TOTAL_LABEL);
        total.setIncomingBandwidth(incomingBandwidth);
        total.setOutgoingBandwidth(outgoingBandwidth);
        switch (index) {
        case REG_BANDWIDTH_INDEX:
            tenantUsage.setTotalRegistryBandwidth(total);
            break;
        case SVC_BANDWIDTH_INDEX:
            tenantUsage.setTotalServiceBandwidth(total);
            break;
        case WEBAPP_BANDWIDTH_INDEX:
            tenantUsage.setTotalWebappBandwidth(total);
            break;
        }
        ++index;
    }

    // the users count will be calculated only if the yearMonth is the current yearMonth
    if (isCurrentMonth) {
        int usersCount = getCurrentUserCount(tenantId);
        tenantUsage.setNumberOfUsers(usersCount);
    }
    // get the API invocation data
    APIManagerUsageStats[] apiStats = null;
    try {
        apiStats = getAPIManagerUsageStats(tenantId, startDate, endDate, isCurrentMonth);
    } catch (Exception e) {
        String msg = "Error in getting bandwidth statistics from metering service.";
        log.error(msg, e);
        throw new Exception(msg, e);
    }
    tenantUsage.setApiManagerUsageStats(apiStats);

    //retrieving cartridge hours
    CartridgeStatistics[] cartridgeStatistics = getCartridgeStatistics(tenantId, startDate, endDate,
            isCurrentMonth);
    tenantUsage.setCartridgeStatistics(cartridgeStatistics);
    long totalCartridgeHours = 0;
    if (cartridgeStatistics != null && cartridgeStatistics.length > 0) {

        for (CartridgeStatistics cs : cartridgeStatistics) {
            totalCartridgeHours += cs.getCartridgeHours();
        }
    }

    CartridgeStatistics totalCS = new CartridgeStatistics();
    totalCS.setCartridgeHours(totalCartridgeHours);

    tenantUsage.setTotalCartridgeHours(totalCS);
    return tenantUsage;
}

From source file:org.openlmis.rnr.service.CalculationServiceTest.java

private Date setLineItemDatesAndReturnDate() {
    Calendar currentDate = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Calendar previousDate = (Calendar) currentDate.clone();
    previousDate.add(Calendar.DATE, -5);

    Date authorizedDateOfPreviousLineItem = new Date(previousDate.getTimeInMillis());
    Date createdDateOfCurrentLineItem = new Date(currentDate.getTimeInMillis());
    rnr.setCreatedDate(createdDateOfCurrentLineItem);
    return authorizedDateOfPreviousLineItem;
}

From source file:net.basov.ticketinfo.UI.java

public void displayTicketInfo(NFCaDump d, Ticket t, WebView wv) {
    Context c = wv.getContext();/* w  ww  .  j ava  2  s .  co m*/
    if (t.getTicketState() == Ticket.TS_UNKNOWN)
        t.detectTicketState();
    this.setTicketHeader("h_state", t.getTicketStateAsHTML(c));
    this.setTicketHeader("h_number", t.getTicketNumberAsString());
    if (t.isDebugTimeSet()) {
        String DDDrem;
        if (d.getDDDRem() != null) {
            DDDrem = "<pre style=\"white-space: pre-wrap\">" + d.getDDDRem() + "</pre>";
        } else {
            DDDrem = "";
        }
        this.setTicket("t_debug", "<font color=\"Violet\">Debug time is: "
                + Ticket.DTF.format(t.getTimeToCompare().getTime()) + "</font>" + DDDrem);
    }
    this.setTicket("t_desc", Decode.descCardType(c, t.getTicketType(), t.getTicketTypeVersion()));
    if (t.getValidDays() != 0) {
        this.setTicket("t_valid_days", t.getValidDaysAsString(c));
    }

    if (t.getIssued() != null) {
        if (t.getTicketClass() == Ticket.C_UNLIM_DAYS) {
            if (t.getTripSeqNumber() != 0 && t.getUseTillDate() != null) {
                Calendar toCal = (Calendar) t.getUseTillDate().clone();
                toCal.add(Calendar.MINUTE, t.getFirstUseTime());
                Calendar fromCal = (Calendar) toCal.clone();
                fromCal.add(Calendar.DATE, -1 * t.getValidDays());
                this.setTicket("t_from_datetime", String.format("%s", Ticket.DTF.format(fromCal.getTime())));
                this.setTicket("t_to_datetime", String.format("%s", Ticket.DTF.format(toCal.getTime())));
            } else if (t.getStartUseTill() != null) {
                this.setTicket("t_start_use_till", Ticket.DTF.format(t.getStartUseTill().getTime()));
            }

        } else {
            Calendar toCal = (Calendar) t.getIssued().clone();
            toCal.add(Calendar.DATE, t.getValidDays());
            this.setTicket("t_from_date", String.format("%s", Ticket.DF.format(t.getIssued().getTime())));
            this.setTicket("t_to_date", String.format("%s", Ticket.DF.format(toCal.getTime())));
        }
    }

    if (t.getTicketClass() != Ticket.C_UNLIM_DAYS) {
        if (t.getStartUseBefore() != null) {
            if (t.getIssued() != null) {
                Calendar tmpCal = (Calendar) t.getIssued().clone();
                tmpCal.add(Calendar.DATE, t.getValidDays());
                if (t.getStartUseBefore().after(tmpCal))
                    this.setTicket("t_start_use_before", t.getStartUseBeforeAsString());
            } else
                this.setTicket("t_start_use_before", t.getStartUseBeforeAsString());
        }
    }

    if (t.getStartUseTill() != null && t.getTicketClass() == Ticket.C_UNLIM_DAYS) {
        this.setTicket("t_start_use_till", Ticket.DTF.format(t.getStartUseTill().getTime()));
    }

    if (t.getPassesLeft() > 0)
        this.setTicket("t_trips_left", t.getPassesLeftAsString());
    if ((t.getTurnstileEntered() != 0) || (t.getEntranceEntered() != 0)) {
        this.setTicket("t_trip_seq_number", t.getTripSeqNumbetAsString());
        if (t.getTripStart() != null) {
            this.setTicket("t_trip_start_date", Ticket.DF.format(t.getTripStart().getTime()));
            this.setTicket("t_trip_start_time", Ticket.TF.format(t.getTripStart().getTime()));
        }
        if (t.getTurnstileEntered() != 0) {
            this.setTicket("t_station_id", t.getTurnstileEnteredAsString());
            this.setTicket("t_station", t.getTurnstileDescAsHTML(c));
        } else if (t.getEntranceEntered() != 0) {
            this.setTicket("t_station_id", t.getEntranceEnteredAsString());
            this.setTicket("t_station", t.getStationDescAsHTML(c));
        }
        this.setTicket("t_transport_type", t.getTransportTypeAsHTML(c));
    }
    // TODO: move to web interface
    if (t.getTicketClass() == Ticket.C_90UNIVERSAL) {
        this.setTicket("t_90m_header_fake", "  ");
        StringBuilder sb = new StringBuilder();
        if (t.getT90TripTimeLeft() > 0) {
            sb.append("  ");
            sb.append(c.getString(R.string.t90m_trip_time_left));
            sb.append(": ");
            sb.append(t.getReadableTime(t.getT90TripTimeLeft()));
        } else {
            sb.append("  ");
            sb.append(c.getString(R.string.t90m_trip_time_finished));
        }
        sb.append('\n');
        sb.append("  ");
        sb.append(c.getString(R.string.t90m_metro_trip_is));
        sb.append(" ");
        if (t.getT90MCount() > 0) {
            sb.append(c.getString(R.string.t90m_metro_used));
        } else {
            sb.append(c.getString(R.string.t90m_metro_trip_possible));
        }
        sb.append('\n');
        switch (t.getLayout()) {
        case 13:
            sb.append("  ");
            sb.append(c.getString(R.string.t90m_ground_count));
            sb.append(": ");
            sb.append(t.getT90GCount());
            sb.append('\n');
            break;
        case 10:
            break;
        }
        if (t.getT90RelChangeTime() != 0) {
            sb.append("  ");
            sb.append(c.getString(R.string.t90m_change_time));
            sb.append(": ");
            sb.append(Ticket.TF.format(t.getT90ChangeTime().getTime()));
            sb.append(String.format(" (%02d min)", t.getT90RelChangeTime()));
            sb.append('\n');
        }
        this.setTicket("t_90m_details", sb.toString());
    }
    this.setTicket("t_file_name", t.getFileName() + Ticket.FILE_EXT);
    if (t.getRealFileName() != null && !t.getRealFileName().equals(t.getFileName() + Ticket.FILE_EXT))
        this.setTicket("t_real_file_name", t.getRealFileName());
    if (d.getRemark().length() > 0)
        this.setTicket("t_note_text", d.getRemark());
    this.setTicket("t_layout", t.getTicketLayoutAsString());
    this.setTicket("t_app_id", t.getTicketAppIDAsString());
    this.setTicket("t_type_id", t.getTicketTypeAsString());
    this.setTicket("t_hash", t.getHashAsHexString());
    this.setTicket("t_number", t.getTicketNumberAsString());
    this.setTicket("t_ic_uid", d.getUIDAsString());
    if (!t.isTicketFormatValid())
        this.setTicket("t_dump_crc16", Ticket.getDumpCRC16AsHexString(t.getDump()));
    if (t.getParserError() != null && t.getParserError().length() != 0)
        this.setTicket("t_parser_error",
                "<font color=\"red\">Parser error:\n  " + t.getParserError() + "</font>");
    this.setTicket("i_manufacturer", d.getManufacturerAsHTML());
    this.setTicket("i_chip_names", d.getChipNamesAsHTML());
    this.setTicket("i_std_bytes", d.getChipCapacityAsHTML());
    this.setTicket("i_read_pages", d.getPagesReadAsHTML());
    this.setTicket("i_read_bytes", d.getBytesReadAsHTML());
    this.setTicket("i_uid_hi", d.getUIDHiasHTML());
    this.setTicket("i_uid_lo", d.getUIDLoasHTML());
    this.setTicket("i_bcc0", d.getBCC0AsHTML());
    this.setTicket("i_bcc1", d.getBCC1AsHTML());
    this.setTicket("i_crc_status", d.getUIDCRCStatusAsHTML());
    this.setTicket("i_otp", d.getOTPAsHTML());
    if (d.isSAKNotEmpty())
        this.setIC("i_sak", d.getSAKAsHTML());
    if (d.isATQANotEmpty())
        this.setIC("i_atqa", d.getATQAAsHTML());
    if (d.isVERSIONNotEmpty())
        this.setIC("i_get_version", d.getVERSIONAsHTML());
    if (d.isCountersNotEmpty())
        this.setIC("i_counters", d.getCountersAsHTML());
    if (d.isSIGNNotEmpty())
        this.setIC("i_read_sig", d.getSIGNAsHTML());
    if (d.isAtechListNotEmpty())
        this.setIC("i_tech", d.getATechAsHTML());
    this.setDump(d.getDumpAsHTMLString());
    this.displayMainScreen(wv);
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

private static String coord_futureRange_sync(int startOffset, int endOffset, int instance) throws Exception {
    final XLog LOG = XLog.getLog(CoordELFunctions.class);
    final Thread currentThread = Thread.currentThread();
    ELEvaluator eval = ELEvaluator.getCurrent();
    String retVal = "";
    int datasetFrequency = (int) getDSFrequency();// in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1];
    Calendar nominalInstanceCal = getCurrentInstance(getActionCreationtime(), instCount);
    StringBuilder resolvedInstances = new StringBuilder();
    StringBuilder resolvedURIPaths = new StringBuilder();
    if (nominalInstanceCal != null) {
        Calendar initInstance = getInitialInstanceCal();
        nominalInstanceCal = (Calendar) initInstance.clone();
        nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);

        SyncCoordDataset ds = (SyncCoordDataset) eval.getVariable(DATASET);
        if (ds == null) {
            throw new RuntimeException("Associated Dataset should be defined with key " + DATASET);
        }/*www . ja v  a 2 s.  c  om*/
        String uriTemplate = ds.getUriTemplate();
        Configuration conf = (Configuration) eval.getVariable(CONFIGURATION);
        if (conf == null) {
            throw new RuntimeException("Associated Configuration should be defined with key " + CONFIGURATION);
        }
        int available = 0, checkedInstance = 0;
        boolean resolved = false;
        String user = ParamChecker.notEmpty((String) eval.getVariable(OozieClient.USER_NAME),
                OozieClient.USER_NAME);
        String doneFlag = ds.getDoneFlag();
        URIHandlerService uriService = Services.get().get(URIHandlerService.class);
        URIHandler uriHandler = null;
        Context uriContext = null;
        try {
            while (instance >= checkedInstance && !currentThread.isInterrupted()) {
                ELEvaluator uriEval = getUriEvaluator(nominalInstanceCal);
                String uriPath = uriEval.evaluate(uriTemplate, String.class);
                if (uriHandler == null) {
                    URI uri = new URI(uriPath);
                    uriHandler = uriService.getURIHandler(uri);
                    uriContext = uriHandler.getContext(uri, conf, user, true);
                }
                String uriWithDoneFlag = uriHandler.getURIWithDoneFlag(uriPath, doneFlag);
                if (uriHandler.exists(new URI(uriWithDoneFlag), uriContext)) {
                    if (available == endOffset) {
                        LOG.debug("Matched future(" + available + "): " + uriWithDoneFlag);
                        resolved = true;
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal));
                        resolvedURIPaths.append(uriPath);
                        retVal = resolvedInstances.toString();
                        eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());
                        break;
                    } else if (available >= startOffset) {
                        LOG.debug("Matched future(" + available + "): " + uriWithDoneFlag);
                        resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal))
                                .append(INSTANCE_SEPARATOR);
                        resolvedURIPaths.append(uriPath).append(INSTANCE_SEPARATOR);

                    }
                    available++;
                }
                // nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), datasetFrequency);
                nominalInstanceCal = (Calendar) initInstance.clone();
                instCount[0]++;
                nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency);
                checkedInstance++;
                // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag());
            }
            if (!StringUtils.isEmpty(resolvedURIPaths.toString())
                    && eval.getVariable(CoordELConstants.RESOLVED_PATH) == null) {
                eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString());
            }

        } finally {
            if (uriContext != null) {
                uriContext.destroy();
            }
        }
        if (!resolved) {
            // return unchanged future function with variable 'is_resolved'
            // to 'false'
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE);
            if (startOffset == endOffset) {
                retVal = "${coord:future(" + startOffset + ", " + instance + ")}";
            } else {
                retVal = "${coord:futureRange(" + startOffset + ", " + endOffset + ", " + instance + ")}";
            }
        } else {
            eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE);
        }
    } else {// No feasible nominal time
        eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE);
        retVal = "";
    }
    return retVal;
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

private static String coord_currentRange_sync(int start, int end) throws Exception {
    final XLog LOG = XLog.getLog(CoordELFunctions.class);
    int datasetFrequency = getDSFrequency();// in minutes
    TimeUnit dsTimeUnit = getDSTimeUnit();
    int[] instCount = new int[1];// used as pass by ref
    Calendar nominalInstanceCal = getCurrentInstance(getActionCreationtime(), instCount);
    if (nominalInstanceCal == null) {
        LOG.warn("If the initial instance of the dataset is later than the nominal time, an empty string is"
                + " returned. This means that no data is available at the current-instance specified by the user"
                + " and the user could try modifying his initial-instance to an earlier time.");
        return "";
    } else {/*from www. ja  va  2s. c om*/
        Calendar initInstance = getInitialInstanceCal();
        // Add in the reverse order - newest instance first.
        nominalInstanceCal = (Calendar) initInstance.clone();
        nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), (instCount[0] + start) * datasetFrequency);
        List<String> instances = new ArrayList<String>();
        for (int i = start; i <= end; i++) {
            if (nominalInstanceCal.compareTo(initInstance) < 0) {
                LOG.warn("If the initial instance of the dataset is later than the current-instance specified,"
                        + " such as coord:current({0}) in this case, an empty string is returned. This means that"
                        + " no data is available at the current-instance specified by the user and the user could"
                        + " try modifying his initial-instance to an earlier time.", start);
            } else {
                instances.add(DateUtils.formatDateOozieTZ(nominalInstanceCal));
            }
            nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), datasetFrequency);
        }
        instances = Lists.reverse(instances);
        return StringUtils.join(instances, CoordELFunctions.INSTANCE_SEPARATOR);
    }
}

From source file:com.alkacon.opencms.calendar.CmsCalendarMonthBean.java

/**
 * Builds the HTML output to create a basic calendar month overview.<p>
 * /* w w w.  j a  v  a2  s.c  o  m*/
 * This method serves as a simple example to create a basic html calendar monthly view.<p>
 * 
 * @param year the year of the month to display
 * @param month the month to display 
 * @param calendarLocale the Locale for the calendar to determine the start day of the weeks
 * @param showNavigation if true, navigation links to switch the month are created, otherwise not
 * @return the HTML output to create a basic calendar month overview
 */
public String buildCalendarMonth(int year, int month, Locale calendarLocale, boolean showNavigation) {

    StringBuffer result = new StringBuffer(1024);

    Map dates = getMonthDaysMatrix(year, month, calendarLocale);
    Map monthEntries = getEntriesForMonth(year, month);

    // calculate the start day of the week
    Calendar calendar = new GregorianCalendar(calendarLocale);
    int weekStart = calendar.getFirstDayOfWeek();
    // store current calendar date
    Calendar currentCalendar = (Calendar) calendar.clone();

    // init the date format symbols
    DateFormatSymbols calendarSymbols = new DateFormatSymbols(calendarLocale);

    // open the table
    result.append("<table class=\"");
    result.append(getStyle().getStyleTable());
    result.append("\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n");

    // create the calendar navigation row
    result.append(buildMonthNavigation(year, month, currentCalendar, calendarLocale, showNavigation));

    // create the week day row
    result.append("<tr>\n");
    int currWeekDay = weekStart;
    for (int i = 1; i <= 7; i++) {

        result.append("\t<td class=\"");
        result.append(getStyle().getStyleWeekdays());
        result.append("\">");
        result.append(calendarSymbols.getShortWeekdays()[currWeekDay]);
        result.append("</td>\n");
        // check if we are at end of week
        if (currWeekDay == Calendar.SATURDAY) {
            currWeekDay = 0;
        }

        currWeekDay++;
    }
    result.append("</tr>\n");

    // now create the entry rows
    result.append("<tr>\n");

    // iterate the index entries of the matrix
    Iterator i = dates.keySet().iterator();
    while (i.hasNext()) {
        Integer index = (Integer) i.next();
        result.append("\t<td class=\"");
        Calendar currDay = (Calendar) dates.get(index);
        if (currDay != null) {
            // current index represents a day, create day output
            String styleDayCell = getStyle().getStyleDay();
            if (isCurrentDay(currentCalendar, currDay)) {
                // for the current day, use another cell style
                styleDayCell = getStyle().getStyleDayCurrent();
            }
            // get entries for the day
            List dayEntries = (List) monthEntries.get(currDay.getTime());
            if (dayEntries.size() > 0) {
                // current day has calendar entries
                int weekdayStatus = 0;
                int holidayEntries = 0;
                int commonEntries = dayEntries.size();
                StringBuffer dayText = new StringBuffer(128);
                // check all entries for special weekday status entries
                for (int k = 0; k < commonEntries; k++) {
                    CmsCalendarEntry entry = (CmsCalendarEntry) dayEntries.get(k);
                    int entryWeekdayStatus = entry.getEntryData().getWeekdayStatus();
                    if (entryWeekdayStatus > 0) {
                        // entry is a special weekday
                        holidayEntries++;
                        // append special day info to title info
                        dayText.append(entry.getEntryData().getTitle());
                        dayText.append(" - ");
                        if (entryWeekdayStatus > weekdayStatus) {
                            // increase the status of the weekday
                            weekdayStatus = entryWeekdayStatus;
                        }
                    }
                }
                // calculate the count of common calendar entries
                commonEntries = commonEntries - holidayEntries;
                // determine the CSS class to use
                String dayStyle = getWeekdayStyle(currDay.get(Calendar.DAY_OF_WEEK), weekdayStatus);
                result.append(styleDayCell);
                result.append("\" title=\"");
                result.append(dayText);
                // check the number of common entries and generate output of entry count
                if (commonEntries <= 0) {
                    // no entry found
                    result.append(getMessages().key("calendar.entries.count.none"));
                } else if (commonEntries == 1) {
                    // one entry found
                    result.append(getMessages().key("calendar.entries.count.one"));
                } else {
                    // more than one entry found
                    result.append(getMessages().key("calendar.entries.count.more",
                            new String[] { String.valueOf(commonEntries) }));
                }
                result.append("\">");
                if (commonEntries > 0) {
                    // common entries present, create link to the overview page 
                    result.append("<a href=\"");
                    result.append(createLink(currDay, m_viewUri, true, -1));
                    result.append("\" class=\"");
                    result.append(getStyle().getStyleDayEntryLink());
                    result.append("\">");
                }
                result.append("<span class=\"");
                result.append(dayStyle);
                result.append("\">");
                result.append(currDay.get(Calendar.DAY_OF_MONTH));
                result.append("</span>");
                if (commonEntries > 0) {
                    // common entries present, close link
                    result.append("</a>");
                }
            } else {
                // current day has no entries
                result.append(styleDayCell);
                result.append("\" title=\"");
                result.append(getMessages().key("calendar.entries.count.none"));
                result.append("\">");
                result.append("<span class=\"");
                result.append(getWeekdayStyle(currDay.get(Calendar.DAY_OF_WEEK),
                        I_CmsCalendarEntryData.WEEKDAYSTATUS_WORKDAY));
                result.append("\">");
                result.append(currDay.get(Calendar.DAY_OF_MONTH));
                result.append("</span>");
            }
        } else {
            // this is an empty cell
            result.append(getStyle().getStyleDayEmpty());
            result.append("\">");
        }
        result.append("</td>\n");
        if ((index.intValue() % 7) == 0) {
            // append closing row tag
            result.append("</tr>\n");
            if (i.hasNext()) {
                // open next row if more elements are present
                result.append("<tr>\n");
            }
        }
    }

    // close the table
    result.append("</table>");
    return result.toString();
}