Example usage for java.sql Timestamp setNanos

List of usage examples for java.sql Timestamp setNanos

Introduction

In this page you can find the example usage for java.sql Timestamp setNanos.

Prototype

public void setNanos(int n) 

Source Link

Document

Sets this Timestamp object's nanos field to the given value.

Usage

From source file:net.sinequanon.grails.StructuredDateOrTimestampEditor.java

@SuppressWarnings("rawtypes")
public Object assemble(Class type, Map fieldValues) throws IllegalArgumentException {
    String yearString = (String) fieldValues.get("year");
    String monthString = (String) fieldValues.get("month");
    String dayString = (String) fieldValues.get("day");
    String hourString = (String) fieldValues.get("hour");
    String minuteString = (String) fieldValues.get("minute");
    String secondString = (String) fieldValues.get("second");
    String milliSecondString = (String) fieldValues.get("millisecond");
    String nanoSecondString = (String) fieldValues.get("nanosecond");
    String epochString = (String) fieldValues.get("epoch");
    if (StringUtils.isBlank(yearString) && StringUtils.isBlank(monthString) && StringUtils.isBlank(dayString)
            && StringUtils.isBlank(hourString) && StringUtils.isBlank(minuteString)
            && StringUtils.isBlank(secondString) && StringUtils.isBlank(milliSecondString)
            && StringUtils.isBlank(nanoSecondString) && StringUtils.isBlank(epochString)) {
        if (this.myAllowEmpty) {
            setValue(null);// ww  w.  j av a 2s .c  o m
            return null;
        }
        throw new IllegalArgumentException("Date struct values cannot all be empty");
    }

    try {
        Calendar c = null;
        long epoch = 0;
        if (!StringUtils.isBlank(epochString)) {
            epoch = getLongValue(fieldValues, "epoch", 0);
        } else {
            int year = getIntegerValue(fieldValues, "year", 1970);
            int month = getIntegerValue(fieldValues, "month", 1);
            int day = getIntegerValue(fieldValues, "day", 1);
            int hour = getIntegerValue(fieldValues, "hour", 0);
            int minute = getIntegerValue(fieldValues, "minute", 0);
            int second = getIntegerValue(fieldValues, "second", 0);
            int milliSecond = getIntegerValue(fieldValues, "millisecond", 0);
            c = new GregorianCalendar(year, month - 1, day, hour, minute, second);
            epoch = c.getTimeInMillis() + milliSecond;
        }
        if (type == java.util.Date.class) {
            setValue(new java.util.Date(epoch));
            return (getValue());
        }
        if (type == java.sql.Date.class) {
            setValue(new java.sql.Date(epoch));
            return (getValue());
        }
        if (type == java.sql.Timestamp.class) {
            java.sql.Timestamp ts = new java.sql.Timestamp(epoch);
            if (fieldValues.containsKey("nanosecond") && !StringUtils.isBlank(nanoSecondString)) {
                ts.setNanos(getIntegerValue(fieldValues, "nanosecond", 0));
            }
            setValue(ts);
            return ts;
        }
        if (c == null) {
            c = new GregorianCalendar();
            c.setTimeInMillis(epoch);
        }
        setValue(c);
        return c;
    } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException("Bad number format: " + nfe.getMessage());
    }
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

public int storeData(DataList list) {
    try {/*  ww w . ja  v  a2s .  c o  m*/
        Connection conn = dataSourceWrite.getConnection();
        if (conn != null) {
            int i;
            DataItem item;
            EventItem event;
            Object tag;

            conn.setAutoCommit(false);
            PreparedStatement stmt;

            Date t1 = new Date();

            stmt = conn.prepareStatement(sqlInsertStmt);
            for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                if (!(item instanceof EventItem))
                    continue;
                event = (EventItem) item;
                ValueItem val = event.getValue();

                tag = this.getTagOfDp(event.getDp());
                if (tag == null)
                    continue;

                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String)
                    stmt.setString(1, (String) tag);

                java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS());
                ts.setNanos(event.getNanos());

                stmt.setTimestamp(2, ts, cal);

                Double dval = val.getDouble();
                if (dval != null) {
                    stmt.setDouble(3, dval);
                } else {
                    stmt.setNull(3, Types.DOUBLE);
                }

                // value_string                    
                stmt.setString(4, val.getString());

                // value_timestamp
                if (val.getTimeMS() != null)
                    stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal);
                else
                    stmt.setNull(5, Types.TIMESTAMP);

                // status, manager, user
                if (event.hasAttributes()) {
                    stmt.setLong(6, event.getStatus());
                    stmt.setInt(7, event.getManager());
                    stmt.setInt(8, event.getUser());
                } else {
                    stmt.setNull(6, Types.INTEGER);
                    stmt.setNull(7, Types.INTEGER);
                    stmt.setNull(8, Types.INTEGER);
                }

                //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()});

                stmt.addBatch();
            }
            try {
                stmt.executeBatch(); // TODO check result? int[] res =
            } catch (BatchUpdateException ex) {
                JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.",
                        new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length });
                JDebug.StackTrace(Level.SEVERE, ex);
            } catch (SQLException ex) {
                SQLException current = ex;
                do {
                    JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() });
                    JDebug.StackTrace(Level.SEVERE, current);
                } while ((current = current.getNextException()) != null);
                //                    for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                //                        JDebug.out.log(Level.INFO, "{0}", item.toJSONObject());
                //                    }
            }
            Date t2 = new Date();
            stmt.close();

            afterInsert(conn);

            conn.commit();
            conn.close();
            addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime());
            return INoSQLInterface.OK;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
            return INoSQLInterface.ERR_REPEATABLE;
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
        return INoSQLInterface.ERR_REPEATABLE;
    }
}

From source file:com.commander4j.util.JUtility.java

/**
 * Method getTimestampFromDate./*from   ww w.jav a2 s .  c o m*/
 * 
 * @param d
 *            Date
 * @return Timestamp
 */
public static Timestamp getTimestampFromDate(Date d) {
    Calendar caldate = Calendar.getInstance();
    caldate.setTime(d);

    Timestamp t = new Timestamp(caldate.getTimeInMillis());
    t.setNanos(0);
    t.setTime(caldate.getTimeInMillis());

    return t;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getDayStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0,
            0, 0);/*from   www.  j  a v a 2s.  c o  m*/
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    return retStamp;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getMonthStart(Timestamp stamp, int daysLater, int monthsLater, TimeZone timeZone,
        Locale locale) {// w  ww . j a  va  2  s . c  o  m
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), 1, 0, 0, 0);
    tempCal.add(Calendar.MONTH, monthsLater);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    return retStamp;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getYearStart(Timestamp stamp, int daysLater, int monthsLater, int yearsLater,
        TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), Calendar.JANUARY, 1, 0, 0, 0);
    tempCal.add(Calendar.YEAR, yearsLater);
    tempCal.add(Calendar.MONTH, monthsLater);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    return retStamp;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getDayEnd(Timestamp stamp, Long daysLater, TimeZone timeZone, Locale locale) {
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 23,
            59, 59);//  ww w  .ja v a 2  s. c om
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater.intValue());
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    // MSSQL datetime field has accuracy of 3 milliseconds and setting the
    // nano seconds cause the date to be rounded to next day
    // retStamp.setNanos(999999999);
    return retStamp;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

public static Timestamp getWeekStart(Timestamp stamp, int daysLater, int weeksLater, TimeZone timeZone,
        Locale locale) {/*from ww  w  .jav  a2s  .c  o m*/
    Calendar tempCal = toCalendar(stamp, timeZone, locale);
    tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0,
            0, 0);
    tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
    tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
    tempCal.add(Calendar.WEEK_OF_MONTH, weeksLater);
    Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
    retStamp.setNanos(0);
    return retStamp;
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Formats a timestamp according to {@link #CKAN_TIMESTAMP_PATTERN}, with
 * precision up to microseconds./*from   w w w . jav a2s .c om*/
 *
 * @see #parseTimestamp(java.lang.String) for the inverse process.
 * @since 0.4.1
 */
@Nullable
public static String formatTimestamp(Timestamp timestamp) {
    if (timestamp == null) {
        throw new IllegalArgumentException("Found null timestamp!");
    }
    Timestamp ret = Timestamp.valueOf(timestamp.toString());
    ret.setNanos((timestamp.getNanos() / 1000) * 1000);
    return Strings.padEnd(ret.toString().replace(" ", "T"), "1970-01-01T01:00:00.000001".length(), '0');
}

From source file:com.twineworks.kettle.ruby.step.execmodels.SimpleExecutionModel.java

private void applyRubyHashToRow(Object[] r, RubyHash resultRow, List<ValueMetaInterface> forFields,
        RowMetaInterface forRow) throws KettleException {

    // set each field's value from the resultRow
    for (ValueMetaInterface outField : forFields) {

        IRubyObject rubyVal = resultRow.fastARef(data.rubyStringCache.get(outField.getName()));

        // convert simple cases automatically
        Object javaValue = null;/*from w  ww  .jav  a 2 s  .  c om*/

        // for nil values just put null into the row
        if (rubyVal != null && !rubyVal.isNil()) {

            // TODO: provide a meaningful error message if conversion fails because the user put non-convertible results in there (like a string saying "true"/"false" for the bool type)
            switch (outField.getType()) {
            case ValueMetaInterface.TYPE_BOOLEAN:
                javaValue = JavaEmbedUtils.rubyToJava(data.runtime, rubyVal, Boolean.class);
                break;
            case ValueMetaInterface.TYPE_INTEGER:
                javaValue = JavaEmbedUtils.rubyToJava(data.runtime, rubyVal, Long.class);
                break;
            case ValueMetaInterface.TYPE_STRING:
                javaValue = rubyVal.toString();
                break;
            case ValueMetaInterface.TYPE_NUMBER:
                javaValue = JavaEmbedUtils.rubyToJava(data.runtime, rubyVal, Double.class);
                break;
            case ValueMetaInterface.TYPE_SERIALIZABLE:
                String marshalled = getMarshal().callMethod(data.runtime.getCurrentContext(), "dump", rubyVal)
                        .toString();
                javaValue = new RubyStepMarshalledObject(marshalled);
                break;
            case ValueMetaInterface.TYPE_BINARY:
                // TODO: provide meaningful error message if this fails
                RubyArray arr = rubyVal.convertToArray();

                byte[] bytes = new byte[arr.size()];
                for (int i = 0; i < bytes.length; i++) {
                    Object rItem = arr.get(i);
                    if (rItem instanceof Number) {
                        bytes[i] = ((Number) rItem).byteValue();
                    } else {
                        throw new KettleException("Found a non-number in Binary field " + outField.getName()
                                + ": " + rItem.toString());
                    }
                }
                javaValue = bytes;
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
                if (rubyVal instanceof RubyFloat) {
                    javaValue = new BigDecimal((Double) rubyVal.toJava(Double.class));
                } else {
                    javaValue = new BigDecimal(rubyVal.toString());
                }

                break;
            case ValueMetaInterface.TYPE_DATE:
                if (rubyVal instanceof RubyFixnum) {
                    javaValue = new Date(((RubyFixnum) rubyVal).getLongValue());
                } else if (rubyVal instanceof RubyTime) {
                    javaValue = ((RubyTime) rubyVal).getJavaDate();
                } else {
                    throw new KettleException(
                            "cannot convert ruby value " + rubyVal.toString() + " to java Date");
                }
                break;

            case ValueMetaInterface.TYPE_TIMESTAMP:
                if (rubyVal instanceof RubyFixnum) {
                    javaValue = new java.sql.Timestamp(((RubyFixnum) rubyVal).getLongValue());
                } else if (rubyVal instanceof RubyTime) {
                    RubyTime time = (RubyTime) rubyVal;
                    long millis = time.getDateTime().getMillis();
                    Timestamp ts = new java.sql.Timestamp(millis / 1000 * 1000);
                    ts.setNanos((int) ((time.getNSec()) + (millis % 1000 * 1000000)));
                    javaValue = ts;
                } else {
                    throw new KettleException(
                            "cannot convert ruby value " + rubyVal.toString() + " to java.sql.Timestamp");
                }
                break;

            case ValueMetaInterface.TYPE_INET:
                Long longNum = (Long) data.container.callMethod(rubyVal, "to_i");
                javaValue = toInetAddress(longNum.intValue());
                break;

            }

        }

        r[data.fieldIndexCache.get(forRow).get(outField.getName())] = javaValue;
    }

}