List of usage examples for java.sql Timestamp getNanos
public int getNanos()
From source file:jp.co.ctc_g.jfw.core.util.Dates.java
/** * <p>//from w w w .j av a 2 s .c o m * ?????????. * </p> * @param date ?? * @param type ?????? * @return ??? */ public static Date truncate(Date date, DateType type) { Calendar currentCalendar = Dates.getCalendarInstance(date); int year = currentCalendar.get(Calendar.YEAR); int month = currentCalendar.get(Calendar.MONTH); int day = currentCalendar.get(Calendar.DATE); int hour = currentCalendar.get(Calendar.HOUR_OF_DAY); int minute = currentCalendar.get(Calendar.MINUTE); int second = currentCalendar.get(Calendar.SECOND); int millis = currentCalendar.get(Calendar.MILLISECOND); if (Objects.equals(type, Dates.YEAR)) { month = 0; day = 1; hour = 0; minute = 0; second = 0; millis = 0; } else if (Objects.equals(type, Dates.MONTH)) { day = 1; hour = 0; minute = 0; second = 0; millis = 0; } else if (Objects.equals(type, Dates.DAY)) { hour = 0; minute = 0; second = 0; millis = 0; } else if (Objects.equals(type, Dates.HOUR)) { minute = 0; second = 0; millis = 0; } else if (Objects.equals(type, Dates.MINUTE)) { second = 0; millis = 0; } else if (Objects.equals(type, Dates.SECOND)) { millis = 0; } else if (Objects.equals(type, Dates.MSEC)) { /* * Timestamp?????? ???????????????????? */ if (date instanceof java.sql.Timestamp) { // ??? java.sql.Timestamp timestamp = (java.sql.Timestamp) date; millis = timestamp.getNanos() / NANOS_2_MSEC; } } currentCalendar.set(year, month, day, hour, minute, second); currentCalendar.set(Calendar.MILLISECOND, millis); long afterMillis = currentCalendar.getTimeInMillis(); /* * ???????????? Calendar????????java.util.Date??????? */ return instantiateDate(date.getClass(), afterMillis); }
From source file:org.isatools.isatab_v1.DublinTestSet.java
@SuppressWarnings("static-access") private void persist(String path) throws IOException { out.println("\n\n_________ Loading and mapping: " + path + " _______\n\n"); String baseDir = System.getProperty("basedir"); String filesPath = baseDir + path; ISATABLoader loader = new ISATABLoader(filesPath); FormatSetInstance isatabInstance = loader.load(); out.println("\n\n_____ Loaded, now mapping"); BIIObjectStore store = new BIIObjectStore(); ISATABMapper isatabMapper = new ISATABMapper(store, isatabInstance); isatabMapper.map();/*from w w w . ja v a 2 s .c om*/ assertTrue("Oh no! No mapped object! ", store.size() > 0); out.println("\n_____________ Persisting"); // Test the repository too String repoPath = baseDir + "/target/bii_test_repo/meta_data"; File repoDir = new File(repoPath); if (!repoDir.exists()) { FileUtils.forceMkdir(repoDir); } if (!transaction.isActive()) { transaction.begin(); } ISATABPersister persister = new ISATABPersister(store, DaoFactory.getInstance(entityManager)); Timestamp ts = persister.persist(filesPath); transaction.commit(); for (Study study : store.valuesOfType(Study.class)) { assertTrue("Oh no! Submission didn't go to the repository!", new File(repoPath + "/" + DataLocationManager.getObfuscatedStudyFileName(study)).exists()); } out.println("\n\n\n\n_______________ Done, Submission TS: " + ts.getTime() + " (" + ts + " + " + ts.getNanos() + "ns)"); }
From source file:com.rogchen.common.xml.UtilDateTime.java
/** * ? Timestamp // w w w .j a va 2 s. c o m * * @param from * @param thru * @return */ public static double getInterval(Timestamp from, Timestamp thru) { return thru != null ? thru.getTime() - from.getTime() + (thru.getNanos() - from.getNanos()) / 1000000 : 0; }
From source file:org.isatools.isatab_v1.IconixPersistenceTest.java
@SuppressWarnings("static-access") @Test/*from ww w .j a va 2 s .com*/ public void testPersistence() throws Exception { out.println("\n\n_______________________ Iconix Case Persistence Test _______________________\n\n"); String baseDir = System.getProperty("basedir"); String filesPath = baseDir + "/target/test-classes/test-data/isatab/isatab_v1_200810/iconix_20081107red"; ISATABLoader loader = new ISATABLoader(filesPath); FormatSetInstance isatabInstance = loader.load(); out.println("\n\n_____ Loaded, now mapping"); BIIObjectStore store = new BIIObjectStore(); ISATABMapper isatabMapper = new ISATABMapper(store, isatabInstance); isatabMapper.map(); assertTrue("Oh no! No mapped object! ", store.size() > 0); out.println("\n_____________ Persisting"); // Test the repository too String repoPath = baseDir + "/target/bii_test_repo/meta_data"; File repoDir = new File(repoPath); if (!repoDir.exists()) { FileUtils.forceMkdir(repoDir); } ISATABPersister persister = new ISATABPersister(store, DaoFactory.getInstance(entityManager)); Timestamp ts = persister.persist(filesPath); transaction.commit(); for (Study study : store.valuesOfType(Study.class)) { assertTrue("Oh no! Submission didn't go to the repository!", new File(repoPath + "/study_" + DataLocationManager.getObfuscatedStudyFileName(study)) .exists()); } out.println("\n\n\n\n________________ Done, Submission TS: " + ts.getTime() + " (" + ts + " + " + ts.getNanos() + "ns)"); out.println("\n\n___________________ /end: Iconix Case Persistence Test ___________________\n\n"); }
From source file:org.apache.olingo.client.core.v3.PrimitiveValueTest.java
@Test public void dateTime() throws EdmPrimitiveTypeException { final Calendar expected = Calendar.getInstance(); expected.clear();//from w w w. j a v a2 s. co m expected.set(2013, 0, 10, 2, 0, 0); expected.set(Calendar.MILLISECOND, 1667673); final ODataValue value = getClient().getObjectFactory().newPrimitiveValueBuilder() .setType(EdmPrimitiveTypeKind.DateTime).setValue(expected).build(); assertEquals(EdmPrimitiveTypeKind.DateTime, value.asPrimitive().getTypeKind()); final Calendar actual = value.asPrimitive().toCastValue(Calendar.class); assertEquals(expected.get(Calendar.YEAR), actual.get(Calendar.YEAR)); assertEquals(expected.get(Calendar.MONTH), actual.get(Calendar.MONTH)); assertEquals(expected.get(Calendar.DATE), actual.get(Calendar.DATE)); assertEquals(expected.get(Calendar.HOUR), actual.get(Calendar.HOUR)); assertEquals(expected.get(Calendar.MINUTE), actual.get(Calendar.MINUTE)); assertEquals(expected.get(Calendar.SECOND), actual.get(Calendar.SECOND)); assertEquals(expected.get(Calendar.MILLISECOND), actual.get(Calendar.MILLISECOND)); // Timestamp final Timestamp timestamp = value.asPrimitive().toCastValue(Timestamp.class); assertEquals(expected.get(Calendar.MILLISECOND), timestamp.getNanos() / 1000000); assertEquals("2013-01-10T02:27:47.673", value.asPrimitive().toString()); }
From source file:org.apache.olingo.client.core.v3.PrimitiveValueTest.java
@Test public void dateTimeOffset() throws EdmPrimitiveTypeException { final Calendar expected = Calendar.getInstance(); expected.clear();//from ww w .j a v a 2 s .com expected.setTimeZone(TimeZone.getTimeZone("GMT")); expected.set(2013, 0, 10, 2, 0, 0); expected.set(Calendar.MILLISECOND, 22); final ODataValue value = getClient().getObjectFactory().newPrimitiveValueBuilder() .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(expected).build(); assertEquals(EdmPrimitiveTypeKind.DateTimeOffset, value.asPrimitive().getTypeKind()); final Calendar asCalendar = value.asPrimitive().toCastValue(Calendar.class); assertEquals(expected.get(Calendar.YEAR), asCalendar.get(Calendar.YEAR)); assertEquals(expected.get(Calendar.MONTH), asCalendar.get(Calendar.MONTH)); assertEquals(expected.get(Calendar.DATE), asCalendar.get(Calendar.DATE)); assertEquals(expected.get(Calendar.HOUR), asCalendar.get(Calendar.HOUR)); assertEquals(expected.get(Calendar.MINUTE), asCalendar.get(Calendar.MINUTE)); assertEquals(expected.get(Calendar.SECOND), asCalendar.get(Calendar.SECOND)); assertEquals(expected.get(Calendar.MILLISECOND), asCalendar.get(Calendar.MILLISECOND)); final Timestamp asTimestamp = value.asPrimitive().toCastValue(Timestamp.class); assertEquals(expected.get(Calendar.MILLISECOND), asTimestamp.getNanos() / 1000000); assertEquals("2013-01-10T02:00:00.022Z", value.asPrimitive().toString()); final ODataValue parsed = getClient().getObjectFactory().newPrimitiveValueBuilder() .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(value.asPrimitive().toValue()).build(); assertEquals(22, parsed.asPrimitive().toCastValue(Calendar.class).get(Calendar.MILLISECOND)); }
From source file:org.mule.modules.clarizen.api.ClarizenDateConverter.java
/** * Convert the input object into a Date object of the * specified type./*www.j a v a2s . c o m*/ * <p> * This method handles conversions between the following * types: * <ul> * <li><code>javax.xml.datatype.XMLGregorianCalendar</code></li> * <li><code>java.util.Date</code></li> * <li><code>java.util.Calendar</code></li> * <li><code>java.sql.Date</code></li> * <li><code>java.sql.Time</code></li> * <li><code>java.sql.Timestamp</code></li> * </ul> * * It also handles conversion from a <code>String</code> to * any of the above types. * <p> * * For <code>String</code> conversion, if the converter has been configured * with one or more patterns (using <code>setPatterns()</code>), then * the conversion is attempted with each of the specified patterns. * Otherwise the default <code>DateFormat</code> for the default locale * (and <i>style</i> if configured) will be used. * * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully */ @SuppressWarnings("rawtypes") protected Object convertToType(Class targetType, Object value) throws Exception { Class sourceType = value.getClass(); // For XMLGregorianCalendar if (value instanceof XMLGregorianCalendar) { XMLGregorianCalendar gregorianCalendar = (XMLGregorianCalendar) value; return toDate(targetType, gregorianCalendar.toGregorianCalendar().getTime().getTime()); } // Handle java.sql.Timestamp if (value instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp) value; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; // ---------------------- JDK 1.3 Fix ---------------------- return toDate(targetType, timeInMillis); } // Handle Date (includes java.sql.Date & java.sql.Time) if (value instanceof Date) { Date date = (Date) value; return toDate(targetType, date.getTime()); } // Handle Calendar if (value instanceof Calendar) { Calendar calendar = (Calendar) value; return toDate(targetType, calendar.getTime().getTime()); } // Handle Long if (value instanceof Long) { Long longObj = (Long) value; return toDate(targetType, longObj.longValue()); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Parse the Date/Time if (useLocaleFormat) { Calendar calendar = null; if (patterns != null && patterns.length > 0) { calendar = parse(sourceType, targetType, stringValue); } else { DateFormat format = getFormat(locale, timeZone); calendar = parse(sourceType, targetType, stringValue, format); } if (Calendar.class.isAssignableFrom(targetType)) { return calendar; } else { return toDate(targetType, calendar.getTime().getTime()); } } // Default String conversion return toDate(targetType, stringValue); }
From source file:com.google.visualization.datasource.util.SqlDataSourceHelper.java
/** * Creates a table cell from the value in the current row of the given result * set and the given column index. The type of the value is determined by the * given value type./* w w w.j a va2 s. c o m*/ * * @param rs The result set holding the data from the sql table. The result * points to the current row. * @param valueType The value type of the column that the cell belongs to. * @param column The column index. Indexes are 0-based. * * @return The table cell. * * @throws SQLException Thrown when the connection to the database failed. */ private static TableCell buildTableCell(ResultSet rs, ValueType valueType, int column) throws SQLException { Value value = null; // SQL indexes are 1- based. column = column + 1; switch (valueType) { case BOOLEAN: value = BooleanValue.getInstance(rs.getBoolean(column)); break; case NUMBER: value = new NumberValue(rs.getDouble(column)); break; case DATE: Date date = rs.getDate(column); // If date is null it is handled later. if (date != null) { GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Set the year, month and date in the gregorian calendar. // Use the 'set' method with those parameters, and not the 'setTime' // method with the date parameter, since the Date object contains the // current time zone and it's impossible to change it to 'GMT'. gc.set(date.getYear() + 1900, date.getMonth(), date.getDate()); value = new DateValue(gc); } break; case DATETIME: Timestamp timestamp = rs.getTimestamp(column); // If timestamp is null it is handled later. if (timestamp != null) { GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Set the year, month, date, hours, minutes and seconds in the // gregorian calendar. Use the 'set' method with those parameters, // and not the 'setTime' method with the timestamp parameter, since // the Timestamp object contains the current time zone and it's // impossible to change it to 'GMT'. gc.set(timestamp.getYear() + 1900, timestamp.getMonth(), timestamp.getDate(), timestamp.getHours(), timestamp.getMinutes(), timestamp.getSeconds()); // Set the milliseconds explicitly, as they are not saved in the // underlying date. gc.set(Calendar.MILLISECOND, timestamp.getNanos() / 1000000); value = new DateTimeValue(gc); } break; case TIMEOFDAY: Time time = rs.getTime(column); // If time is null it is handled later. if (time != null) { GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Set the hours, minutes and seconds of the time in the gregorian // calendar. Set the year, month and date to be January 1 1970 like // in the Time object. // Use the 'set' method with those parameters, // and not the 'setTime' method with the time parameter, since // the Time object contains the current time zone and it's // impossible to change it to 'GMT'. gc.set(1970, Calendar.JANUARY, 1, time.getHours(), time.getMinutes(), time.getSeconds()); // Set the milliseconds explicitly, otherwise the milliseconds from // the time the gc was initialized are used. gc.set(GregorianCalendar.MILLISECOND, 0); value = new TimeOfDayValue(gc); } break; default: String colValue = rs.getString(column); if (colValue == null) { value = TextValue.getNullValue(); } else { value = new TextValue(rs.getString(column)); } break; } // Handle null values. if (rs.wasNull()) { return new TableCell(Value.getNullValueFromValueType(valueType)); } else { return new TableCell(value); } }
From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java
/** * Convert the input object into a Date object of the * specified type.// ww w . jav a 2 s . com * <p> * This method handles conversions between the following * types: * <ul> * <li><code>java.util.Date</code></li> * <li><code>java.util.Calendar</code></li> * <li><code>java.sql.Date</code></li> * <li><code>java.sql.Time</code></li> * <li><code>java.sql.Timestamp</code></li> * </ul> * * It also handles conversion from a <code>String</code> to * any of the above types. * <p> * * For <code>String</code> conversion, if the converter has been configured * with one or more patterns (using <code>setPatterns()</code>), then * the conversion is attempted with each of the specified patterns. * Otherwise the default <code>DateFormat</code> for the default locale * (and <i>style</i> if configured) will be used. * * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully */ protected Object convertToType(Class targetType, Object value) throws Exception { Class sourceType = value.getClass(); // Handle java.sql.Timestamp if (value instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp) value; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; // ---------------------- JDK 1.3 Fix ---------------------- return toDate(targetType, timeInMillis); } // Handle Date (includes java.sql.Date & java.sql.Time) if (value instanceof Date) { Date date = (Date) value; return toDate(targetType, date.getTime()); } // Handle Calendar if (value instanceof Calendar) { Calendar calendar = (Calendar) value; return toDate(targetType, calendar.getTime().getTime()); } // Handle Long if (value instanceof Long) { Long longObj = (Long) value; return toDate(targetType, longObj.longValue()); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Parse the Date/Time if (useLocaleFormat) { Calendar calendar = null; if (patterns != null && patterns.length > 0) { calendar = parse(sourceType, targetType, stringValue); } else { DateFormat format = getFormat(locale, timeZone); calendar = parse(sourceType, targetType, stringValue, format); } if (Calendar.class.isAssignableFrom(targetType)) { return calendar; } else { return toDate(targetType, calendar.getTime().getTime()); } } // Default String conversion return toDate(targetType, stringValue); }
From source file:com.erbjuder.logger.server.soap.services.LogMessageServiceBase.java
public Response create(Transactions transactions) throws WebServiceException { //// w ww. ja v a2 s. c om // Return Response response = new Response(); response.setReturn(true); try { // // Parse SOAP Header and looking for MessageId String message_id = ""; HeaderList headerList = (com.sun.xml.ws.api.message.HeaderList) getWebServiceContext() .getMessageContext().get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY); for (Header header : headerList) { String urn = header.getNamespaceURI(); String key = header.getLocalPart(); String value = header.getStringContent().trim(); if (MESSAGE_ID_URN.equalsIgnoreCase(urn) && MESSAGE_ID.equalsIgnoreCase(key) && !value.isEmpty()) { //logger.log(Level.SEVERE, "[ Found messageId " + value + " ] "); message_id = value; response.setReturn(false); } else { logger.log(Level.SEVERE, "Got <Urn : Key> =[ " + urn + " ] " + " [ " + key + " ]"); } } // // Copy all element into new structure due the original list seams to be NOT modifiable // ( That's a requirement of Collection.sort method ) List<Transactions.Transaction> tmpTransactionList = transactions.getTransaction(); Transactions.Transaction[] transactionArray = tmpTransactionList .toArray(new Transaction[tmpTransactionList.size()]); Arrays.sort(transactionArray, new TransactionComparator()); for (Transactions.Transaction transaction : transactionArray) { LogMessage logMessage = new LogMessage(); // // Mandator String referenceId = transaction.getTransactionReferenceID(); if (message_id.isEmpty() || referenceId.equals(message_id)) { logMessage.setTransactionReferenceID(referenceId); } else { logger.log(Level.SEVERE, "[ TransactionReferanceId don't match SOAP Header content-id ] "); response.setReturn(false); } // // Server UTC time logMessage.setApplicationName(transaction.getApplicationName().toLowerCase()); logMessage.setIsError(transaction.isIsError()); logMessage.setUtcServerTimeStamp(TimeStampUtils.createSystemNanoTimeStamp()); try { long UTCLocalTimeStamp = transaction.getUTCLocalTimeStamp().toGregorianCalendar() .getTimeInMillis(); long UTCLocalTimeStampNanoSeconds = 0; try { UTCLocalTimeStampNanoSeconds = transaction.getUTCLocalTimeStampNanoSeconds(); } catch (Exception UTCLocalTimeStampNanoSecondsNotPressent) { //Skip client nano Timestamp timestamp = new Timestamp(UTCLocalTimeStamp); UTCLocalTimeStampNanoSeconds = timestamp.getNanos(); } if (Long.MAX_VALUE > UTCLocalTimeStamp && Long.MIN_VALUE < UTCLocalTimeStamp) { logger.log(Level.INFO, "UTCLocalTimeStamp=[ " + UTCLocalTimeStamp + " ]"); logger.log(Level.INFO, "UTCLocalTimeStampNanoSeconds=[ " + UTCLocalTimeStampNanoSeconds + " ]"); logger.log(Level.INFO, "createNanoTimeStamp=[ " + TimeStampUtils .createNanoTimeStamp(UTCLocalTimeStamp, UTCLocalTimeStampNanoSeconds) .getNanos() + " ]"); logMessage.setUtcLocalTimeStamp(TimeStampUtils.createNanoTimeStamp(UTCLocalTimeStamp, UTCLocalTimeStampNanoSeconds)); } else { logger.log(Level.INFO, "[ Invalid UTCLocalTimeStamp range, Use current system time instead! ] "); logger.log(Level.INFO, "[ " + UTCLocalTimeStamp + " ] "); logMessage.setUtcLocalTimeStamp(TimeStampUtils.createSystemNanoTimeStamp()); } } catch (Exception invalidDateException) { logger.log(Level.INFO, "[ Invalid log date! Use current system time instead! ] "); logger.log(Level.INFO, invalidDateException.getMessage()); logMessage.setUtcLocalTimeStamp(TimeStampUtils.createSystemNanoTimeStamp()); } // // Optional try { Date expiredTime = transaction.getExpiryDate().toGregorianCalendar().getTime(); if (expiredTime != null && Long.MAX_VALUE > expiredTime.getTime() && Long.MIN_VALUE < expiredTime.getTime()) { logMessage.setExpiredDate(expiredTime); } else { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.MONTH, addNumberOfMonth); logMessage.setExpiredDate(calendar.getTime()); } } catch (Exception invalidExiredDateException) { logger.log(Level.INFO, "[ Invalid ExpiryDate! Use default expired time instead! ] "); logger.log(Level.INFO, invalidExiredDateException.getMessage()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.MONTH, addNumberOfMonth); logMessage.setExpiredDate(calendar.getTime()); } // // Transaction point info if (transaction.getTransactionLogPointInfo() != null) { String flowName = transaction.getTransactionLogPointInfo().getFlowName().trim().toLowerCase(); String flowPointName = transaction.getTransactionLogPointInfo().getFlowPointName().trim() .toLowerCase(); if (flowName.isEmpty()) { flowName = transaction.getApplicationName().trim().toLowerCase(); } if (flowPointName.isEmpty()) { flowPointName = ""; } logMessage.setFlowName(flowName); logMessage.setFlowPointName(flowPointName); } else { logMessage.setFlowName(""); logMessage.setFlowPointName(""); } logger.log(Level.INFO, "Flow done ]"); // // Transaction log data logMessage = this.buildTransactioLogDataEntity(transaction, logMessage); // // Persist getLogMessageFacade().create(logMessage); } } catch (Throwable ex) { StringBuilder builder = new StringBuilder(); builder.append("============= [ Java Server exception ] =============== \n"); builder.append(ex.getMessage()); logger.log(Level.SEVERE, builder.toString()); response.setReturn(false); } // // Return return response; }