Example usage for java.util Calendar getTimeZone

List of usage examples for java.util Calendar getTimeZone

Introduction

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

Prototype

public TimeZone getTimeZone() 

Source Link

Document

Gets the time zone.

Usage

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object dateDiff(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    if (ArgList.length == 3) {
        try {/*from   w ww .  ja va 2 s  .  c  o m*/
            if (isNull(ArgList, new int[] { 0, 1, 2 }))
                return new Double(Double.NaN);
            else if (isUndefined(ArgList, new int[] { 0, 1, 2 }))
                return Context.getUndefinedValue();
            else {
                java.util.Date dIn1 = (java.util.Date) Context.jsToJava(ArgList[0], java.util.Date.class);
                java.util.Date dIn2 = (java.util.Date) Context.jsToJava(ArgList[1], java.util.Date.class);
                String strType = Context.toString(ArgList[2]);
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /* Changed by:    Ingo Klose, SHS VIVEON AG,
                 * Date:      27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results
                 * when crossing Daylight Savingstime borders. In order to get correct results
                 * the time zone offsets have to be added.
                 *
                 * Fix:       1.    calculate correct milli seconds for start and end date
                 *             2.    replace endDate.getTimeInMillis() with endL
                 *                and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.toLowerCase().equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.toLowerCase().equals("m")) {
                    int iMonthsToAdd = (int) (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.toLowerCase().equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.toLowerCase().equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate))
                        iOffset = 1;
                    while (endL < startL || endL > startL) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY))
                            iRC++;
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.toLowerCase().equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.toLowerCase().equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.toLowerCase().equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.toLowerCase().equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                   * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call dateDiff requires 3 arguments.");
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static Object dateDiff(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    if (ArgList.length == 3) {
        try {//from  w ww . java  2 s  .c  o  m
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return undefinedValue;
            } else {
                java.util.Date dIn1 = (java.util.Date) ArgList[0];
                java.util.Date dIn2 = (java.util.Date) ArgList[1];
                String strType = ((String) ArgList[2]).toLowerCase();
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /*
                 * Changed by: Ingo Klose, SHS VIVEON AG, Date: 27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results when crossing Daylight
                 * Savingstime borders. In order to get correct results the time zone offsets have to be added.
                 *
                 * Fix: 1. calculate correct milli seconds for start and end date 2. replace endDate.getTimeInMillis() with
                 * endL and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.equals("m")) {
                    int iMonthsToAdd = (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate)) {
                        iOffset = 1;
                    }
                    while ((iOffset == 1 && endL < startL) || (iOffset == -1 && endL > startL)) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                            iRC++;
                        }
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                 * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
    } else {
        throw new RuntimeException("The function call dateDiff requires 3 arguments.");
    }
}

From source file:org.wso2.carbon.connector.integration.test.gotowebinar.GotowebinarConnectorIntegrationTest.java

/**
 * Method to validate whether pre-requisites are accomplished.
 *
 * @return boolean validation status./*from w  ww.j a  v  a2s.c  o  m*/
 */
private boolean validate() throws IOException, JSONException {
    boolean isValidSession = false;
    boolean isAnyUpcoming = false;

    Calendar calendar = Calendar.getInstance();
    Calendar currentCalendar = Calendar.getInstance();
    DateFormat isoTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String toTime = isoTimeFormat.format(calendar.getTime());
    calendar.add(Calendar.YEAR, -1);
    String fromTime = isoTimeFormat.format(calendar.getTime());

    connectorProperties.put("searchFromTime", fromTime);
    connectorProperties.put("searchToTime", toTime);
    currentCalendar.add(currentCalendar.MONTH, 1);
    connectorProperties.put("webinarStartTime", isoTimeFormat.format(currentCalendar.getTime()));
    currentCalendar.add(currentCalendar.HOUR, 1);
    connectorProperties.put("webinarEndTime", isoTimeFormat.format(currentCalendar.getTime()));
    connectorProperties.put("timeZone", currentCalendar.getTimeZone().getID());
    // Get all Historical webinars with in last year.
    String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/historicalWebinars?fromTime=" + fromTime + "&toTime=" + toTime;
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);
    JSONArray historicalWebinarArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    outerloop: for (int i = 0; i < historicalWebinarArray.length(); i++) {
        String webinarKey = historicalWebinarArray.getJSONObject(i).getString("webinarKey");
        // Get all session details which belongs to the listed webinar.
        apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
                + "/webinars/" + webinarKey + "/sessions";
        apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);
        JSONArray webinarSessionArray = new JSONArray(apiRestResponse.getBody().getString("output"));
        for (int j = 0; j < webinarSessionArray.length(); j++) {
            int noOfRegistrants = webinarSessionArray.getJSONObject(j).getInt("registrantsAttended");

            // If session has one or more registrants all the required properties are set and loop will be
            if (noOfRegistrants > 0) {
                String sessionKey = webinarSessionArray.getJSONObject(j).getString("sessionKey");
                connectorProperties.put("sessionKey", sessionKey);
                connectorProperties.put("webinarKey", webinarKey);
                connectorProperties.put("fromTime", historicalWebinarArray.getJSONObject(i)
                        .getJSONArray("times").getJSONObject(0).getString("startTime"));
                connectorProperties.put("toTime", historicalWebinarArray.getJSONObject(i).getJSONArray("times")
                        .getJSONObject(0).getString("endTime"));
                isValidSession = true;
                break outerloop;
            }
        }
    }
    // List all upcoming webinars
    apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/upcomingWebinars";
    apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);
    JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output"));
    // If there are one or more upcoming webinars #upcomingWebinarKey property will be set
    if (apiResponseArray.length() > 0) {
        isAnyUpcoming = true;
        connectorProperties.put("upcomingWebinarKey",
                apiResponseArray.getJSONObject(0).getString("webinarKey"));
        for (int w = 0; w < apiResponseArray.length(); w++) {
            String upcomingWebinarKeyToDeleteRegistrant = apiResponseArray.getJSONObject(w)
                    .getString("webinarKey");
            connectorProperties.put("upcomingWebinarKeyToDeleteRegistrant",
                    upcomingWebinarKeyToDeleteRegistrant);
            String getSessionsApiEndPoint = apiRequestUrl + "/organizers/"
                    + connectorProperties.getProperty("organizerKey") + "/webinars/"
                    + upcomingWebinarKeyToDeleteRegistrant + "/sessions";
            RestResponse<JSONObject> getSessionsApiRestResponse = sendJsonRestRequest(getSessionsApiEndPoint,
                    "GET", apiRequestHeadersMap);
            JSONArray webinarSessionArray = new JSONArray(
                    getSessionsApiRestResponse.getBody().getString("output"));
            if (!getSessionsApiRestResponse.getBody().getString("output").equals("[]")) {
                String getAttendeesApiEndPoint = apiRequestUrl + "/organizers/"
                        + connectorProperties.getProperty("organizerKey") + "/webinars/"
                        + upcomingWebinarKeyToDeleteRegistrant + "/sessions/"
                        + webinarSessionArray.getJSONObject(0).getString("sessionKey") + "/attendees";
                RestResponse<JSONObject> getAttendeesApiRestResponse = sendJsonRestRequest(
                        getAttendeesApiEndPoint, "GET", apiRequestHeadersMap);
                if (!getAttendeesApiRestResponse.getBody().getString("output").equals("[]")) {
                    JSONArray getAttendeesApiResponseArray = new JSONArray(
                            getAttendeesApiRestResponse.getBody().getString("output"));
                    connectorProperties.put("webinarRegistrantKeyToDelete",
                            getAttendeesApiResponseArray.getJSONObject(0).getString("registrantKey"));
                    break;
                }
            }
            if (StringUtils.isNotEmpty(connectorProperties.getProperty("webinarRegistrantKeyToDelete"))) {
                break;
            } else if (StringUtils.isEmpty(connectorProperties.getProperty("webinarRegistrantKeyToDelete"))
                    && w == apiResponseArray.length() - 1) {
                Assert.fail("Any of the upcoming webinar has attendee for past session.");
            }
        }
    }
    return (isValidSession && isAnyUpcoming);
}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static Object dateDiff(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    if (ArgList.length == 3) {
        try {// w w  w  . ja va2  s.c om
            if (isNull(ArgList, new int[] { 0, 1, 2 })) {
                return new Double(Double.NaN);
            } else if (isUndefined(ArgList, new int[] { 0, 1, 2 })) {
                return Context.getUndefinedValue();
            } else {
                java.util.Date dIn1 = (java.util.Date) Context.jsToJava(ArgList[0], java.util.Date.class);
                java.util.Date dIn2 = (java.util.Date) Context.jsToJava(ArgList[1], java.util.Date.class);
                String strType = Context.toString(ArgList[2]).toLowerCase();
                int iRC = 0;

                Calendar startDate = Calendar.getInstance();
                Calendar endDate = Calendar.getInstance();
                startDate.setTime(dIn1);
                endDate.setTime(dIn2);

                /*
                 * Changed by: Ingo Klose, SHS VIVEON AG, Date: 27.04.2007
                 *
                 * Calculating time differences using getTimeInMillis() leads to false results when crossing Daylight
                 * Savingstime borders. In order to get correct results the time zone offsets have to be added.
                 *
                 * Fix: 1. calculate correct milli seconds for start and end date 2. replace endDate.getTimeInMillis() with
                 * endL and startDate.getTimeInMillis() with startL
                 */
                long endL = endDate.getTimeInMillis()
                        + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                long startL = startDate.getTimeInMillis()
                        + startDate.getTimeZone().getOffset(startDate.getTimeInMillis());

                if (strType.equals("y")) {
                    return new Double(endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
                } else if (strType.equals("m")) {
                    int iMonthsToAdd = (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)) * 12;
                    return new Double(
                            (endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH)) + iMonthsToAdd);
                } else if (strType.equals("d")) {
                    return new Double(((endL - startL) / 86400000));
                } else if (strType.equals("wd")) {
                    int iOffset = -1;
                    if (endDate.before(startDate)) {
                        iOffset = 1;
                    }
                    while ((iOffset == 1 && endL < startL) || (iOffset == -1 && endL > startL)) {
                        int day = endDate.get(Calendar.DAY_OF_WEEK);
                        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
                            iRC++;
                        }
                        endDate.add(Calendar.DATE, iOffset);
                        endL = endDate.getTimeInMillis()
                                + endDate.getTimeZone().getOffset(endDate.getTimeInMillis());
                    }
                    return new Double(iRC);
                } else if (strType.equals("w")) {
                    int iDays = (int) ((endL - startL) / 86400000);
                    return new Double(iDays / 7);
                } else if (strType.equals("ss")) {
                    return new Double(((endL - startL) / 1000));
                } else if (strType.equals("mi")) {
                    return new Double(((endL - startL) / 60000));
                } else if (strType.equals("hh")) {
                    return new Double(((endL - startL) / 3600000));
                } else {
                    return new Double(((endL - startL) / 86400000));
                }
                /*
                 * End Bugfix
                 */
            }
        } catch (Exception e) {
            throw Context.reportRuntimeError(e.toString());
        }
    } else {
        throw Context.reportRuntimeError("The function call dateDiff requires 3 arguments.");
    }
}

From source file:org.globus.workspace.scheduler.defaults.pilot.PilotSlotManagement.java

/**
 *
 * The pilot reports that it has been interrupted and has determined the
 * signal was unexpected.  This can happen in three situations:
 *
 * 1. The LRM or administrator has decided to preempt the pilot for
 * whatever reason./*from   w  w  w .  j  a  va 2 s  . c o m*/
 *
 * 2. The node has been rebooted or shutdown.
 *
 * 3. The LRM job was cancelled by the slot manager (this class).
 * 
 * In each situation the pilot attempts to wait a specific (configurable)
 * ratio of the provided grace period.  In cases #1 and #2 this gives the
 * slot manager time to handle the problem (currently this involves running
 * shutdown-trash on all VMs in the slot).  In case #3 the slot manager can
 * just ignore this notification since it is already done with the slot
 * (which is why it cancelled the LRM job).
 *
 * @param slotid uuid
 * @param hostname hostname
 * @param timestamp the time that pilot sent this (second resolution only)
 *                  used to compute if we should act on it
 */
public void earlyUnreserving(String slotid, String hostname, Calendar timestamp) {
    try {
        // SlotNotFoundException expected if we called qdel
        // (which is the usual situation)
        PilotSlot slot = this.db.getSlot(slotid, hostname);

        StringBuffer buf = new StringBuffer();
        buf.append("Pilot '").append(slotid);

        if (hostname != null) {
            buf.append("' @ host '").append(hostname);
        }
        buf.append("' is being preempted early. Cancelling vm #").append(slot.vmid);

        // Just before the notification was sent
        long timestampLong = timestamp.getTimeInMillis();

        // Now, which could be at any arbitrary time.
        Calendar now = Calendar.getInstance();
        long nowLong = Calendar.getInstance().getTimeInMillis();

        long difference = nowLong - timestampLong;
        difference = difference / 1000; //convert to seconds

        // Because this is an unusual situation, do a lot of logging
        localFormat.setCalendar(timestamp);
        int timestampGMTOffset = timestamp.getTimeZone().getRawOffset();
        buf.append(" || Notification sent @ ").append(localFormat.format(timestamp.getTime()))
                .append(" -- GMT offset ").append(timestampGMTOffset);

        localFormat.setCalendar(now);
        int nowGMTOffset = now.getTimeZone().getRawOffset();
        buf.append(" || Now: ").append(localFormat.format(now.getTime())).append(" -- GMT offset ")
                .append(nowGMTOffset);

        // This check is mostly here if the service was down and the
        // notification consumer is only now getting to the notifications.
        // We allow for a certain amount of inaccuracy on top of the grace
        // period (e.g. only using second resolution on the timestamp).

        int horizon = this.grace + 2;
        boolean trash = true;
        if (difference > horizon) {
            trash = false;
        }

        buf.append(" || Difference in seconds is ").append(difference).append(" which means we will ");

        if (!trash) {
            buf.append("not ");
        }
        buf.append("run shutdown-trash now (difference ");
        if (trash) {
            buf.append(" < ");
        } else {
            buf.append(" > ");
        }
        buf.append("than now + ").append(horizon).append(" seconds.");

        final String msg = buf.toString();
        if (lager.eventLog) {
            logger.info(Lager.ev(slot.vmid) + msg);
        } else {
            logger.debug(Lager.ev(slot.vmid) + msg);
        }

        final Exception e = new Exception("early LRMS preemption");
        if (trash) {
            this.cancelWorkspace(slot.vmid, e);
        } else {
            this.cancelWorkspaceNoTrash(slot.vmid, e);
        }

        this.db.setSlotTerminal(slot);

    } catch (WorkspaceDatabaseException e) {
        final String msg = getDBError("starting early-unreserving", slotid, hostname, e.getMessage());
        logger.error(msg, e);
    } catch (SlotNotFoundException e) {

        String id = "'" + slotid + "'";
        if (hostname != null) {
            id += " @ host '" + hostname + "'";
        }

        logger.debug("Pilot " + id + " is being preempted and "
                + "we do not have a record of this slot anymore.  This "
                + "is the expected situation if we have called qdel (this "
                + "could also have happened if the service just " + "recovered from being down).");
    }
}

From source file:net.starschema.clouddb.jdbc.ScrollableResultset.java

/** {@inheritDoc} */
@Override/*from   w  w  w .  j  a v a 2s.  c  o  m*/
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
    Long value = this.getLong(columnIndex);
    if (this.wasNull()) {
        return null;
    } else {
        return new java.sql.Timestamp(cal.getTimeZone().getRawOffset() + value);
    }
}

From source file:net.starschema.clouddb.jdbc.ScrollableResultset.java

/** {@inheritDoc} */
@Override//from   ww w . jav  a  2s .c o  m
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
    Long value = this.getLong(columnIndex);
    if (this.wasNull()) {
        return null;
    } else {
        return new java.sql.Date(value + cal.getTimeZone().getRawOffset());
    }
}

From source file:net.starschema.clouddb.jdbc.ScrollableResultset.java

/** {@inheritDoc} */
@Override/*  w w  w  .j av  a  2  s .co m*/
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
    /*
     * Select STRFTIME_UTC_USEC(NOW(),'%x-%X%Z') AS One,
     * FORMAT_UTC_USEC(NOW()) as Two"; Result: One Two 08/21/12-15:40:45GMT
     * 2012-08-21 15:40:45.703908
     */
    Long value = this.getLong(columnIndex);
    if (this.wasNull()) {
        return null;
    } else {
        return new java.sql.Time(cal.getTimeZone().getRawOffset() + value);
    }
}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

/**
 * formats a 12hr time display string/* w  w w . jav  a 2 s  .  com*/
 * @param context a context
 * @param cal a Calendar representing some point in time
 * @return a time display string (24 hr) (short format)
 */
public TimeDisplayText calendarTime12HrDisplayString(Context context, @NonNull Calendar cal,
        boolean showSeconds) {
    // some locales use (or optionally allow) 12 hr time;
    //
    // `getTimeFormat` produces a localized timestring but we want the time part (6:47)
    // separate from the suffix (AM/PM) in order to let the layout define the presentation.
    //
    // a. The ICU4j `getPatternInstance` method seems to be the ideal solution (using the
    // HOURS_MINUTES pattern), but is a recent addition to android (api 24).
    //
    // b. Using toLocalizedPattern on an existing SimpleDateFormat
    // may be another solution, but leaves the problem of separating the time from the suffix
    // in a consistent way for all locales.
    //
    // c. Java 8 may introduce methods that address this, but the project currently compiles
    // using older versions of java (and it would suck to break that).
    //
    // d. A third party lib might address this, which could be added if its source is available
    // and easily included in the build from official maven repos.
    //
    // For now the work around is to define a "veryShortFormat" in strings.xml for those locales
    // that use something other than the usual "h:mm" pattern. A better solution would get this
    // from the system somehow without requiring additional translation.

    // a variety 12 hour time formats from around the world...
    //
    //   english (us):       6:47 AM        11:46 PM           (en)
    //   afrikaans:          6:47 vm.       11:46 nm.
    //   isiZulu:            6:47 Ekuseni   11:46 Ntambama
    //   bahasa (melayu):    6:47 PG        11:46 PTG
    //   bahasa (indonesia): 6.47 AM        11.46 PM           (in)
    //   dansk               6.47 AM        11.46 PM           (da)
    //   norsk bokmal        6.47 a.m.      11.46 p.m.         (nb)

    Locale locale = getLocale();

    String format = (showSeconds ? strTimeVeryShortFormat12s : strTimeVeryShortFormat12); // h:mm or h:mm:ss
    SimpleDateFormat timeFormat = new SimpleDateFormat(format, locale);
    timeFormat.setTimeZone(cal.getTimeZone());

    //Log.d("DEBUG","TimeFormat: " + timeFormat.toPattern() + " (" + locale.toString() + ")");

    SimpleDateFormat suffixFormat = new SimpleDateFormat(strTimeSuffixFormat, locale); // a
    suffixFormat.setTimeZone(cal.getTimeZone());

    Date time = cal.getTime();
    TimeDisplayText retValue = new TimeDisplayText(timeFormat.format(time), "", suffixFormat.format(time));
    retValue.setRawValue(cal.getTimeInMillis());
    return retValue;
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Create a new Chart to show only those channels which are selected.
 * This must work even if the ChannelSelector is NULL.
 *
 * @param chartui//from   ww w. j av a2s  . c  o  m
 * @param dao
 * @param datasettype
 * @param primarydataset
 * @param secondarydatasets
 * @param updatetype
 * @param isrefreshable
 * @param isclickrefresh
 * @param displaylimit
 * @param domainstartpoint
 * @param domainendpoint
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

private static JFreeChart createChartForSelection(final ChartUIComponentPlugin chartui,
        final ObservatoryInstrumentDAOInterface dao, final DatasetType datasettype,
        final XYDataset primarydataset, final List<XYDataset> secondarydatasets,
        final DataUpdateType updatetype, final boolean isrefreshable, final boolean isclickrefresh,
        final int displaylimit, final int domainstartpoint, final int domainendpoint,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "ChartHelper.createChartForSelection() ";
    final JFreeChart jFreeChart;

    LOGGER.debug(debug, SOURCE);

    if ((datasettype != null) && (primarydataset != null) && (secondarydatasets != null)
            && (updatetype != null)) {
        final XYDataset xyNewPrimaryDataset;
        final List<XYDataset> listNewSecondaryDatasets;
        final List<XYDataset> listParentSecondaryDatasetForSeries;
        final Iterator iterOriginalSecondaryDatasets;
        final Calendar calObservatory;

        // Create a list of NewSecondaryDatasets for display
        // Add an appropriate *empty* new dataset for every one existing in the secondary set
        // and record the parent new Dataset for each Series in each original Dataset
        // So much complexity just to handle the very few cases of secondary datasets...

        listNewSecondaryDatasets = new ArrayList<XYDataset>(10);
        listParentSecondaryDatasetForSeries = new ArrayList<XYDataset>(10);

        iterOriginalSecondaryDatasets = secondarydatasets.iterator();

        // Either find the Current Observatory calendar, or provide a default
        calObservatory = ObservatoryInstrumentHelper.getCurrentObservatoryCalendar(REGISTRY.getFramework(), dao,
                debug);
        while (iterOriginalSecondaryDatasets.hasNext()) {
            final XYDataset xyDatasetOriginal;

            xyDatasetOriginal = (XYDataset) iterOriginalSecondaryDatasets.next();

            if ((xyDatasetOriginal != null) && (xyDatasetOriginal.getSeriesCount() > 0)) {
                final XYDataset xyDatasetNew;

                // Create an empty Dataset to correspond with the original
                if (datasettype.getName().equals(DatasetType.XY.getName())) {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else if (datasettype.getName().equals(DatasetType.TIMESTAMPED.getName())) {
                    xyDatasetNew = new TimeSeriesCollection(calObservatory.getTimeZone());
                    listNewSecondaryDatasets.add(xyDatasetNew);
                } else {
                    xyDatasetNew = new XYSeriesCollection();
                    listNewSecondaryDatasets.add(xyDatasetNew);
                }

                // Record the *same* parent Dataset for each Series in each original Secondary Dataset
                // This creates a List in channel order, but with references to Datasets not Series
                for (int i = 0; i < xyDatasetOriginal.getSeriesCount(); i++) {
                    listParentSecondaryDatasetForSeries.add(xyDatasetNew);
                }
            }
        }

        LOGGER.debug(debug, SOURCE + "Check the DatasetType");

        // Confirm the DatasetType
        if ((datasettype.getName().equals(DatasetType.XY.getName()))
                && (primarydataset instanceof XYSeriesCollection)) {
            final XYSeriesCollection collectionPrimary;

            // Prepare a new XYSeriesCollection for display
            xyNewPrimaryDataset = new XYSeriesCollection();

            // There should be a collection of <channelcount> XYSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (XYSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)) {
                final int intChannelCount;

                if (channelselector != null) {
                    channelselector.debugSelector(debug, SOURCE);

                    if ((channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        intChannelCount = channelselector.getChannelSelectionModes().size();
                        LOGGER.debug(debug, SOURCE + "[channelcount.channelselector=" + intChannelCount + "]");
                    } else if (dao != null) {
                        intChannelCount = dao.getRawDataChannelCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.dao.raw=" + intChannelCount
                                + "] (has channelselector?)");
                    } else {
                        intChannelCount = collectionPrimary.getSeriesCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.primary.series=" + intChannelCount + "]");
                    }
                } else if (dao != null) {
                    intChannelCount = dao.getRawDataChannelCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.dao.raw" + intChannelCount + "] (no channelselector)");
                } else {
                    // This should never happen!
                    intChannelCount = collectionPrimary.getSeriesCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.primary.series" + intChannelCount + "] (last resort)");
                }

                LOGGER.debug(debug,
                        SOURCE + DatasetType.XY.getName() + " [domain.start.point=" + domainstartpoint
                                + "] [domain.end.point=" + domainendpoint + "] [channelcount.inferred="
                                + intChannelCount + "]");

                // Find which channels to use this time round
                for (int intChannelIndex = 0; intChannelIndex < intChannelCount; intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    // Use the ChannelSelectionMode if we can
                    if ((channelselector != null) && (channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);
                    } else {
                        // If there is no ChannelSelector then we can safely assume the Channel is ON
                        selectionMode = ChannelSelectionMode.X1;
                    }

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final XYSeries seriesOriginalData;

                        seriesOriginalData = (XYSeries) getSeriesForIndex(datasettype, primarydataset,
                                secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final XYSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new XYSeries(seriesOriginalData.getKey());

                            // Map the slider values to data indexes
                            intStartIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                    DatasetDomainUIComponentInterface.INDEX_LEFT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.XY, calObservatory,
                                    seriesOriginalData, debug);

                            intEndIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                    DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.XY, calObservatory,
                                    seriesOriginalData, debug);
                            if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                // If either index is returned as -1, then there's nothing to do...
                                // ...so stop the for() loop
                                intStartIndex = 0;
                                intEndIndex = 0;
                            } else if (intEndIndex <= intStartIndex) {
                                intEndIndex = intStartIndex + 1;
                            }

                            LOGGER.debug(debug,
                                    SOURCE + "before copy of selected series subset [channel=" + intChannelIndex
                                            + "] [index.start=" + intStartIndex + "] [index.end=" + intEndIndex
                                            + "] [show.ticks=" + ((intEndIndex - intStartIndex) <= 25) + "]");

                            // Copy over only the selected range from the Slider
                            for (int intDataIndex = intStartIndex; ((intDataIndex < intEndIndex)
                                    && (listOriginalDataItems.size() > 0)); intDataIndex++) {
                                final XYDataItem dataOriginalItem;
                                final XYDataItem dataChangedItem;

                                dataOriginalItem = (XYDataItem) listOriginalDataItems.get(intDataIndex);

                                if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                    // Change each value of the series according to the multiplier
                                    dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                            dataOriginalItem.getY().doubleValue()
                                                    * selectionMode.getMultiplier());
                                } else {
                                    // Just use the whole series unaltered for gain of X1
                                    dataChangedItem = new XYDataItem(dataOriginalItem.getX(),
                                            dataOriginalItem.getY());
                                }

                                seriesChangedData.add(dataChangedItem);
                            }

                            // Place the changed series in the correct collection
                            // to correspond with the original

                            // Did we collect any data for this Series?
                            // If not, place a dummy point at the origin of the *visible* chart
                            if (seriesChangedData.getItemCount() == 0) {
                                // TODO
                                seriesChangedData.add(new XYDataItem(0, 0));
                            }

                            if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                // Simply add the changed Primary series to the PrimaryDataset collection
                                ((XYSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                            } else {
                                // It must be a secondary dataset
                                // Add the changed Secondary series to the parent SecondaryDataset
                                // given by the *secondary* channel index
                                addSecondarySeries(datasettype, listParentSecondaryDatasetForSeries,
                                        seriesChangedData,
                                        intChannelIndex - collectionPrimary.getSeriesCount());
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData XYSeries unexpectedly NULL");
                        }
                    }
                }

                // Dump the (partial) contents of each Series in the composite XYdataset
                dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "XYSeriesCollection --> createCustomisedChart() xyNewPrimaryDataset");

                jFreeChart = chartui.createCustomisedChart(datasettype, xyNewPrimaryDataset,
                        listNewSecondaryDatasets, updatetype, displaylimit, channelselector, debug);
            } else {
                LOGGER.error(SOURCE + " The XYSeriesCollection does not have any XYSeries");
                jFreeChart = null;
            }
        } else if ((datasettype.getName().equals(DatasetType.TIMESTAMPED.getName()))
                && (primarydataset instanceof TimeSeriesCollection)) {
            final TimeSeriesCollection collectionPrimary;

            // Prepare a new TimeSeriesCollection for display
            xyNewPrimaryDataset = new TimeSeriesCollection(calObservatory.getTimeZone());

            // There should be a collection of <channelcount> TimeSeries in the Primary Dataset
            // but there may also be some in the Secondary Datasets
            collectionPrimary = (TimeSeriesCollection) primarydataset;

            if ((collectionPrimary.getSeriesCount() > 0) && (collectionPrimary.getSeries() != null)) {
                final int intChannelCount;

                if (channelselector != null) {
                    channelselector.debugSelector(debug, SOURCE);

                    if ((channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        intChannelCount = channelselector.getChannelSelectionModes().size();
                        LOGGER.debug(debug, SOURCE + "[channelcount.channelselector=" + intChannelCount + "]");
                    } else if (dao != null) {
                        intChannelCount = dao.getRawDataChannelCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.dao.raw=" + intChannelCount
                                + "] (has channelselector)");
                    } else {
                        intChannelCount = collectionPrimary.getSeriesCount();
                        LOGGER.debug(debug, SOURCE + "[channelcount.primary.series=" + intChannelCount + "]");
                    }
                } else if (dao != null) {
                    intChannelCount = dao.getRawDataChannelCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.dao.raw=" + intChannelCount + "] (no channelselector)");
                } else {
                    // This should never happen!
                    intChannelCount = collectionPrimary.getSeriesCount();
                    LOGGER.debug(debug,
                            SOURCE + "[channelcount.primary.series=" + intChannelCount + "] (last resort)");
                }

                LOGGER.debug(debug,
                        SOURCE + DatasetType.TIMESTAMPED.getName() + " [domain.startpoint=" + domainstartpoint
                                + "] [domain.endpoint=" + domainendpoint + "] [domain.lowerbound="
                                + (long) collectionPrimary.getDomainLowerBound(true) + "] [domain.upperbound="
                                + (long) collectionPrimary.getDomainUpperBound(true)
                                + "] [channelcount.inferred=" + intChannelCount + "]");

                // Find which channels to use this time round
                for (int intChannelIndex = 0; intChannelIndex < intChannelCount; intChannelIndex++) {
                    final ChannelSelectionMode selectionMode;

                    // Use the ChannelSelectionMode if we can
                    if ((channelselector != null) && (channelselector.getChannelSelectionModes() != null)
                            && (channelselector.showChannels())) {
                        selectionMode = channelselector.getChannelSelectionModes().get(intChannelIndex);
                    } else {
                        // If there is no ChannelSelector then we can safely assume the Channel is ON
                        selectionMode = ChannelSelectionMode.X1;
                    }

                    if (!ChannelSelectionMode.OFF.equals(selectionMode)) {
                        final TimeSeries seriesOriginalData;

                        seriesOriginalData = (TimeSeries) getSeriesForIndex(datasettype, primarydataset,
                                secondarydatasets, intChannelIndex, debug);
                        if (seriesOriginalData != null) {
                            final TimeSeries seriesChangedData;
                            final List listOriginalDataItems;
                            int intStartIndex;
                            int intEndIndex;

                            listOriginalDataItems = seriesOriginalData.getItems();

                            // Prepare a new Series for the changed data, with the same Key
                            seriesChangedData = new TimeSeries(seriesOriginalData.getKey().toString(),
                                    seriesOriginalData.getTimePeriodClass());

                            // Map the slider values to data indexes
                            intStartIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainstartpoint,
                                    DatasetDomainUIComponentInterface.INDEX_LEFT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                    calObservatory, seriesOriginalData, debug);

                            intEndIndex = transformDomainSliderValueToSeriesIndex(
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MINIMUM,
                                    ChartUIComponentPlugin.DOMAIN_SLIDER_MAXIMUM, domainendpoint,
                                    DatasetDomainUIComponentInterface.INDEX_RIGHT,
                                    collectionPrimary.getDomainLowerBound(true),
                                    collectionPrimary.getDomainUpperBound(true), DatasetType.TIMESTAMPED,
                                    calObservatory, seriesOriginalData, debug);
                            if ((intStartIndex == -1) || (intEndIndex == -1)) {
                                // If either index is returned as -1, then there's nothing to do...
                                // ...so stop the for() loop
                                intStartIndex = 0;
                                intEndIndex = 0;
                            } else if (intEndIndex <= intStartIndex) {
                                intEndIndex = intStartIndex + 1;
                            }

                            LOGGER.debug(debug,
                                    SOURCE + "before copy of selected series subset [channel=" + intChannelIndex
                                            + "] [index.start=" + intStartIndex + "] [index.end=" + intEndIndex
                                            + "] [item.count=" + listOriginalDataItems.size() + "]");

                            // Copy over only the selected range from the Slider
                            for (int intDataIndex = intStartIndex; ((intDataIndex < intEndIndex)
                                    && (intDataIndex < listOriginalDataItems.size())); intDataIndex++) {
                                final TimeSeriesDataItem dataOriginalItem;
                                final TimeSeriesDataItem dataChangedItem;

                                dataOriginalItem = (TimeSeriesDataItem) listOriginalDataItems.get(intDataIndex);

                                if (!ChannelSelectionMode.X1.equals(selectionMode)) {
                                    // Change each value of the series according to the multiplier
                                    dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                            dataOriginalItem.getValue().doubleValue()
                                                    * selectionMode.getMultiplier());
                                } else {
                                    // Just use the whole series unaltered for gain of X1
                                    dataChangedItem = new TimeSeriesDataItem(dataOriginalItem.getPeriod(),
                                            dataOriginalItem.getValue().doubleValue());
                                }

                                seriesChangedData.add(dataChangedItem);
                            }

                            // Did we collect any data for this Series?
                            // If not, place a dummy point at the origin of the *visible* chart
                            if (seriesChangedData.getItemCount() == 0) {
                                seriesChangedData.add(createDummyTimeSeriesDataItemAtOrigin(collectionPrimary,
                                        seriesOriginalData, domainstartpoint, debug));
                            }

                            // Place the changed series in the correct collection
                            // to correspond with the original
                            if (intChannelIndex < collectionPrimary.getSeriesCount()) {
                                // Simply add the changed Primary series to the PrimaryDataset collection
                                ((TimeSeriesCollection) xyNewPrimaryDataset).addSeries(seriesChangedData);
                            } else {
                                // It must be a secondary dataset
                                // Add the changed Secondary series to the parent SecondaryDataset
                                // given by the *secondary* channel index
                                addSecondarySeries(datasettype, listParentSecondaryDatasetForSeries,
                                        seriesChangedData,
                                        intChannelIndex - collectionPrimary.getSeriesCount());
                            }
                        } else {
                            LOGGER.warn(SOURCE + "OriginalData TimeSeries unexpectedly NULL");
                        }
                    }
                }

                // Dump the (partial) contents of each Series in the composite XYdataset
                dumpXYDataset(debug, calObservatory, xyNewPrimaryDataset, 4,
                        SOURCE + "TimeSeriesCollection --> createCustomisedChart() xyNewPrimaryDataset");

                jFreeChart = chartui.createCustomisedChart(datasettype, xyNewPrimaryDataset,
                        listNewSecondaryDatasets, updatetype, displaylimit, channelselector, debug);
            } else {
                LOGGER.error(SOURCE + " The TimeSeriesCollection does not have any TimeSeries");
                jFreeChart = null;
            }
        } else {
            LOGGER.error(SOURCE + " The Dataset is of an invalid type");
            jFreeChart = null;
        }
    } else {
        LOGGER.debug(debug, SOURCE + " Unable to change the Chart - invalid parameters");
        jFreeChart = null;
    }

    return (jFreeChart);
}