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.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testDatetimeWithCalendar() throws SQLException {
    trace("test DATETIME with Calendar");
    ResultSet rs;//from w w w .j  a  v a  2 s  .co m

    stat = conn.createStatement();
    stat.execute("CREATE TABLE test(ID INT PRIMARY KEY, D DATE, T TIME, TS TIMESTAMP)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO test VALUES(?, ?, ?, ?)");
    Calendar regular = Calendar.getInstance();
    Calendar other = null;
    // search a locale that has a _different_ raw offset
    long testTime = java.sql.Date.valueOf("2001-02-03").getTime();
    for (String s : TimeZone.getAvailableIDs()) {
        TimeZone zone = TimeZone.getTimeZone(s);
        long rawOffsetDiff = regular.getTimeZone().getRawOffset() - zone.getRawOffset();
        // must not be the same timezone (not 0 h and not 24 h difference
        // as for Pacific/Auckland and Etc/GMT+12)
        if (rawOffsetDiff != 0 && rawOffsetDiff != 1000 * 60 * 60 * 24) {
            if (regular.getTimeZone().getOffset(testTime) != zone.getOffset(testTime)) {
                other = Calendar.getInstance(zone);
                break;
            }
        }
    }

    trace("regular offset = " + regular.getTimeZone().getRawOffset() + " other = "
            + other.getTimeZone().getRawOffset());

    prep.setInt(1, 0);
    prep.setDate(2, null, regular);
    prep.setTime(3, null, regular);
    prep.setTimestamp(4, null, regular);
    prep.execute();

    prep.setInt(1, 1);
    prep.setDate(2, null, other);
    prep.setTime(3, null, other);
    prep.setTimestamp(4, null, other);
    prep.execute();

    prep.setInt(1, 2);
    prep.setDate(2, java.sql.Date.valueOf("2001-02-03"), regular);
    prep.setTime(3, java.sql.Time.valueOf("04:05:06"), regular);
    prep.setTimestamp(4, Timestamp.valueOf("2007-08-09 10:11:12.131415"), regular);
    prep.execute();

    prep.setInt(1, 3);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"), other);
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"), other);
    prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415"), other);
    prep.execute();

    prep.setInt(1, 4);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"));
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"));
    prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415"));
    prep.execute();

    rs = stat.executeQuery("SELECT * FROM test ORDER BY ID");
    assertResultSetMeta(rs, 4, new String[] { "ID", "D", "T", "TS" },
            new int[] { Types.INTEGER, Types.DATE, Types.TIME, Types.TIMESTAMP }, new int[] { 10, 8, 6, 23 },
            new int[] { 0, 0, 0, 10 });

    rs.next();
    assertEquals(0, rs.getInt(1));
    assertTrue(rs.getDate(2, regular) == null && rs.wasNull());
    assertTrue(rs.getTime(3, regular) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, regular) == null && rs.wasNull());

    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getDate(2, other) == null && rs.wasNull());
    assertTrue(rs.getTime(3, other) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, other) == null && rs.wasNull());

    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals("2001-02-03", rs.getDate(2, regular).toString());
    assertEquals("04:05:06", rs.getTime(3, regular).toString());
    assertFalse(rs.getTime(3, other).toString().equals("04:05:06"));
    assertEquals("2007-08-09 10:11:12.131415", rs.getTimestamp(4, regular).toString());
    assertFalse(rs.getTimestamp(4, other).toString().equals("2007-08-09 10:11:12.131415"));

    rs.next();
    assertEquals(3, rs.getInt("ID"));
    assertFalse(rs.getTimestamp("TS", regular).toString().equals("2107-08-09 10:11:12.131415"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS", other).toString());
    assertFalse(rs.getTime("T", regular).toString().equals("14:05:06"));
    assertEquals("14:05:06", rs.getTime("T", other).toString());
    // checkFalse(rs.getDate(2, regular).toString(), "2101-02-03");
    // check(rs.getDate("D", other).toString(), "2101-02-03");

    rs.next();
    assertEquals(4, rs.getInt("ID"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS").toString());
    assertEquals("14:05:06", rs.getTime("T").toString());
    assertEquals("2101-02-03", rs.getDate("D").toString());

    assertFalse(rs.next());
    stat.execute("DROP TABLE test");
}

From source file:org.kuali.kfs.module.endow.document.service.impl.CurrentTaxLotServiceImpl.java

/**
 * Helper method to calculate the number of days to the last payment
 *///from   w ww.java 2 s .c  om
protected long getTotalDaysToLastPayment(Date lastPaymentDate, Date nextIncomeDueDate) {
    long totalDays = 0;
    long MILLISECS_PER_DAY = (1000 * 60 * 60 * 24); // total milliseconds in a day

    Calendar currentDateCalendar = Calendar.getInstance();
    currentDateCalendar.setTime(kEMService.getCurrentDate());
    currentDateCalendar.set(Calendar.HOUR, 0);
    currentDateCalendar.set(Calendar.MINUTE, 0);
    currentDateCalendar.set(Calendar.SECOND, 0);

    Calendar lastPaymentDateCalendar = Calendar.getInstance();
    lastPaymentDateCalendar.setTime(lastPaymentDate);
    lastPaymentDateCalendar.set(Calendar.HOUR, 0);
    lastPaymentDateCalendar.set(Calendar.MINUTE, 0);
    lastPaymentDateCalendar.set(Calendar.SECOND, 0);

    // to take care of leap year and day light savings time.
    long endL = lastPaymentDateCalendar.getTimeInMillis()
            + lastPaymentDateCalendar.getTimeZone().getOffset(lastPaymentDateCalendar.getTimeInMillis());
    long startL = currentDateCalendar.getTimeInMillis()
            + currentDateCalendar.getTimeZone().getOffset(currentDateCalendar.getTimeInMillis());

    return (endL - startL) / MILLISECS_PER_DAY;
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDatePrinter.java

@Override
public <B extends Appendable> B format(Calendar calendar, final B buf) {
    // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored
    if (!calendar.getTimeZone().equals(mTimeZone)) {
        calendar = (Calendar) calendar.clone();
        calendar.setTimeZone(mTimeZone);
    }//www.  j  a  v  a  2 s.  c o  m
    return applyRules(calendar, buf);
}

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

public TimeDisplayText calendarDateTimeDisplayString(Context context, Calendar cal, boolean showYear,
        boolean showSeconds) {
    if (cal == null || context == null) {
        return new TimeDisplayText(strTimeNone);
    }/*from w  w  w.jav  a2s. c o  m*/

    Locale locale = getLocale();
    SimpleDateFormat dateTimeFormat;

    if (showSeconds)
        dateTimeFormat = new SimpleDateFormat((showYear ? strDateTimeLongFormatSec : strDateTimeShortFormatSec),
                locale);
    else
        dateTimeFormat = new SimpleDateFormat((showYear ? strDateTimeLongFormat : strDateTimeShortFormat),
                locale);

    //Log.d("DEBUG","DateTimeFormat: " + dateTimeFormat.toPattern() + " (" + locale.toString() + ")");

    dateTimeFormat.setTimeZone(cal.getTimeZone());
    TimeDisplayText displayText = new TimeDisplayText(dateTimeFormat.format(cal.getTime()), "", "");
    displayText.setRawValue(cal.getTimeInMillis());
    return displayText;

    // doesn't use the appropriate timezone (always formats to system)
    /**int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME;
    formatFlags = (showYear ? (formatFlags | DateUtils.FORMAT_SHOW_YEAR) : (formatFlags | DateUtils.FORMAT_NO_YEAR));
    return new TimeDisplayText(DateUtils.formatDateRange(context, cal.getTimeInMillis(), cal.getTimeInMillis(), formatFlags), "", "");*/

    // doesn't use app's 12hr/24hr setting, doesn't work w/ custom TimeZone objs
    /**Long time = cal.getTimeInMillis();
    String tzID = cal.getTimeZone().getID();
    Formatter formatter = new Formatter(new StringBuilder(50), Locale.getDefault());
    formatter = DateUtils.formatDateRange(context, formatter, time, time, formatFlags, tzID);
    return new TimeDisplayText(formatter.toString(), "", "");*/

    // doesn't use app's 12hr/24hr setting
    /** DateFormat timeFormat = android.text.format.DateFormat.getLongDateFormat(context);
    String value = timeFormat.format(cal.getTime());*/
}

From source file:org.n52.server.io.render.DiagramRenderer.java

protected JFreeChart renderPreChart(Map<String, OXFFeatureCollection> entireCollMap,
        String[] observedProperties, ArrayList<TimeSeriesCollection> timeSeries, Calendar begin, Calendar end) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // title
            "Date", // x-axis label
            observedProperties[0], // y-axis label
            timeSeries.get(0), // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );//from ww w.  j a  v a  2 s  .c om

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);

    // add additional datasets:
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setRange(begin.getTime(), end.getTime());
    axis.setDateFormatOverride(new SimpleDateFormat());
    axis.setTimeZone(end.getTimeZone());
    for (int i = 1; i < observedProperties.length; i++) {
        XYDataset additionalDataset = timeSeries.get(i);
        plot.setDataset(i, additionalDataset);
        plot.setRangeAxis(i, new NumberAxis(observedProperties[i]));
        // plot.getRangeAxis(i).setRange((Double)
        // overAllSeriesCollection.getMinimum(i),
        // (Double) overAllSeriesCollection.getMaximum(i));
        plot.mapDatasetToRangeAxis(i, i);
        // plot.getDataset().getXValue(i, i);
    }
    return chart;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support.java

public byte[] getTimeBytes(Calendar calendar, TimeUnit precision) {
    byte[] bytes;
    if (precision == TimeUnit.MINUTES) {
        bytes = BLETypeConversions.shortCalendarToRawBytes(calendar, true);
    } else if (precision == TimeUnit.SECONDS) {
        bytes = BLETypeConversions.calendarToRawBytes(calendar, true);
    } else {//from   w  w  w .  j a v a2  s .  co  m
        throw new IllegalArgumentException(
                "Unsupported precision, only MINUTES and SECONDS are supported till now");
    }
    byte[] tail = new byte[] { 0, BLETypeConversions.mapTimeZone(calendar.getTimeZone()) }; // 0 = adjust reason bitflags? or DST offset?? , timezone
    //        byte[] tail = new byte[] { 0x2 }; // reason
    byte[] all = BLETypeConversions.join(bytes, tail);
    return all;
}

From source file:com.mirth.connect.server.migration.Migrate3_0_0.java

private void migrateChannelTable() {
    PreparedStatement preparedStatement = null;
    ResultSet results = null;//  w ww  .j  av a 2  s  . c o m

    try {
        /*
         * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of
         * results. The following error occurs: "ERROR 40XD0: Container has been closed"
         */
        Connection connection = getConnection();
        connection.setAutoCommit(false);

        preparedStatement = connection.prepareStatement(
                "SELECT ID, NAME, DESCRIPTION, IS_ENABLED, VERSION, REVISION, LAST_MODIFIED, SOURCE_CONNECTOR, DESTINATION_CONNECTORS, PROPERTIES, PREPROCESSING_SCRIPT, POSTPROCESSING_SCRIPT, DEPLOY_SCRIPT, SHUTDOWN_SCRIPT FROM OLD_CHANNEL");
        results = preparedStatement.executeQuery();

        while (results.next()) {
            String channelId = "";

            try {
                channelId = results.getString(1);
                String name = results.getString(2);
                String description = results.getString(3);
                Boolean isEnabled = results.getBoolean(4);
                String version = results.getString(5);
                Integer revision = results.getInt(6);

                Calendar lastModified = Calendar.getInstance();
                lastModified.setTimeInMillis(results.getTimestamp(7).getTime());

                String sourceConnector = results.getString(8);
                String destinationConnectors = results.getString(9);
                String properties = results.getString(10);
                String preprocessingScript = results.getString(11);
                String postprocessingScript = results.getString(12);
                String deployScript = results.getString(13);
                String shutdownScript = results.getString(14);

                Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Element element = document.createElement("channel");
                document.appendChild(element);
                DonkeyElement channel = new DonkeyElement(element);

                channel.addChildElement("id", channelId);
                channel.addChildElement("name", name);
                channel.addChildElement("description", description);
                channel.addChildElement("enabled", Boolean.toString(isEnabled));
                channel.addChildElement("version", version);

                DonkeyElement lastModifiedElement = channel.addChildElement("lastModified");
                lastModifiedElement.addChildElement("time", String.valueOf(lastModified.getTimeInMillis()));
                lastModifiedElement.addChildElement("timezone", lastModified.getTimeZone().getDisplayName());

                channel.addChildElement("revision", String.valueOf(revision));

                channel.addChildElementFromXml(sourceConnector).setNodeName("sourceConnector");
                channel.addChildElementFromXml(destinationConnectors).setNodeName("destinationConnectors");
                channel.addChildElementFromXml(properties);

                channel.addChildElement("preprocessingScript", preprocessingScript);
                channel.addChildElement("postprocessingScript", postprocessingScript);
                channel.addChildElement("deployScript", deployScript);
                channel.addChildElement("shutdownScript", shutdownScript);

                String serializedChannel = channel.toXml();

                PreparedStatement updateStatement = null;

                try {
                    updateStatement = connection.prepareStatement(
                            "INSERT INTO CHANNEL (ID, NAME, REVISION, CHANNEL) VALUES (?, ?, ?, ?)");
                    updateStatement.setString(1, channelId);
                    updateStatement.setString(2, name);
                    updateStatement.setInt(3, revision);
                    updateStatement.setString(4, serializedChannel);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                } finally {
                    DbUtils.closeQuietly(updateStatement);
                }
            } catch (Exception e) {
                logger.error("Error migrating channel " + channelId + ".", e);
            }
        }

        connection.commit();
    } catch (SQLException e) {
        logger.error("Error migrating channels.", e);
    } finally {
        DbUtils.closeQuietly(results);
        DbUtils.closeQuietly(preparedStatement);
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.Serializer.java

private String convertCalendarToXMLFormat(Calendar calendar, boolean dateTimePattern) {
    if (dateTimePattern) {
        GregorianCalendar gregCalendar = new GregorianCalendar(calendar.getTimeZone());
        gregCalendar.setTimeInMillis(calendar.getTimeInMillis());

        return df.newXMLGregorianCalendar(gregCalendar).toXMLFormat();
    } else {/*from w  w w .j  a va 2s  . co m*/
        return df.newXMLGregorianCalendarDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, // Calendar.MONTH is zero based, XSD Date datatype's month field starts
                //   with JANUARY as 1.
                calendar.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED).toXMLFormat();
    }
}

From source file:org.n52.server.io.render.DiagramRenderer.java

/**
 * <pre>/* ww w  .  j  a va2  s .c  o m*/
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 *
 * .
 *
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());
    dateAxis.setTimeZone(end.getTimeZone());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) { // dashed
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static Object dateDiff(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    if (ArgList.length == 3) {
        try {/*from w ww .ja v  a2  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];
                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 ((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.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 new RuntimeException(e.toString());
        }
    } else {
        throw new RuntimeException("The function call dateDiff requires 3 arguments.");
    }
}