Java Code Examples for java.sql.Timestamp#valueOf()

The following examples show how to use java.sql.Timestamp#valueOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonRowDeserializationSchema.java    From flink with Apache License 2.0 6 votes vote down vote up
private DeserializationRuntimeConverter createTimestampConverter() {
	return (mapper, jsonNode) -> {
		// according to RFC 3339 every date-time must have a timezone;
		// until we have full timezone support, we only support UTC;
		// users can parse their time as string as a workaround
		TemporalAccessor parsedTimestamp = RFC3339_TIMESTAMP_FORMAT.parse(jsonNode.asText());

		ZoneOffset zoneOffset = parsedTimestamp.query(TemporalQueries.offset());

		if (zoneOffset != null && zoneOffset.getTotalSeconds() != 0) {
			throw new IllegalStateException(
				"Invalid timestamp format. Only a timestamp in UTC timezone is supported yet. " +
					"Format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
		}

		LocalTime localTime = parsedTimestamp.query(TemporalQueries.localTime());
		LocalDate localDate = parsedTimestamp.query(TemporalQueries.localDate());

		return Timestamp.valueOf(LocalDateTime.of(localDate, localTime));
	};
}
 
Example 2
Source File: TestCrossDatabaseAdhocDeepFetch.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public void testOneToManyOneToOneSameAttribute()
{
    Timestamp businessDate = Timestamp.valueOf("2011-09-30 23:59:00.0");
    ParaPositionList list = new ParaPositionList();
    for(int i=0;i<2000;i++)
    {
        ParaPosition pos = new ParaPosition(InfinityTimestamp.getParaInfinity());
        pos.setAccountNumber("777"+i);
        pos.setAccountSubtype(""+(i % 10));
        pos.setBusinessDate(businessDate);
        pos.setProductIdentifier("P"+i);
        list.add(pos);
    }
    list.insertAll();
    Operation operation = ParaPositionFinder.businessDate().eq(businessDate);
    ParaPositionList nonOpList = ParaPositionFinder.findMany(operation);
    nonOpList.deepFetch(ParaPositionFinder.account());
    assertEquals(2009, nonOpList.size());
    int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
    for(ParaPosition p: nonOpList)
    {
        p.getAccount();
    }
    assertEquals(count, MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount());
}
 
Example 3
Source File: TestEmbeddedValueObjects.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public void testType2DatedUpdateUntil()
{
    final Timestamp businessDate = Timestamp.valueOf("2007-09-10 00:00:00.0");
    final EvoTypesRoot root = this.createEvoTypesRoot('B', false, (byte) 1, "update");
    Operation op = EvoType2DatedTxnTypesBFinder.rootEvo().eq(root).and(EvoType2DatedTxnTypesBFinder.businessDate().eq(businessDate));
    assertNull(EvoType2DatedTxnTypesBFinder.findOneBypassCache(op));

    final EvoType2DatedTxnTypesB types = EvoType2DatedTxnTypesBFinder.findOneBypassCache(
            EvoType2DatedTxnTypesBFinder.pk().charAttribute().eq('B').and(
            EvoType2DatedTxnTypesBFinder.pk().booleanAttribute().eq(false)).and(
            EvoType2DatedTxnTypesBFinder.businessDate().eq(businessDate)));
    assertNotNull(types);

    final Timestamp newBusinessDateEnd = Timestamp.valueOf("2007-09-12 18:30:00.0");
    MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
    {
        public Object executeTransaction(MithraTransaction tx) throws Throwable
        {
            types.copyRootEvoUntil(root, newBusinessDateEnd);
            return null;
        }
    });

    assertEquals(newBusinessDateEnd, EvoType2DatedTxnTypesBFinder.findOne(op).getBusinessDateTo());
    assertEquals(newBusinessDateEnd, EvoType2DatedTxnTypesBFinder.findOneBypassCache(op).getBusinessDateTo());
}
 
Example 4
Source File: TimestampTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test04() throws Exception {
    String testTS = "2009-01-1 10:50:0";
    String ExpectedTS = "2009-01-01 10:50:0";
    Timestamp ts = Timestamp.valueOf(testTS);
    Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
    assertEquals(ts, ts2, "Error ts1 != ts2");
}
 
Example 5
Source File: ValueMetaBaseTest.java    From hop with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertStringToTimestampType() throws HopValueException {
  String timestampStringRepresentation = "2018/04/11 16:45:15.000000000";
  Timestamp expectedTimestamp = Timestamp.valueOf( "2018-04-11 16:45:15.000000000" );

  ValueMetaBase base = new ValueMetaString( "ValueMetaStringColumn" );
  base.setConversionMetadata( new ValueMetaTimestamp( "ValueMetaTimestamp" ) );
  Timestamp timestamp = (Timestamp) base.convertDataUsingConversionMetaData( timestampStringRepresentation );
  assertEquals( expectedTimestamp, timestamp );
}
 
Example 6
Source File: TimestampTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test16() {

    Timestamp ts1 = Timestamp.valueOf("1999-12-13 14:15:25.745634");
    Timestamp ts2 = Timestamp.valueOf("1999-11-13 15:15:25.645634");
    assertFalse(ts1.before(ts2), "Error ts1 before ts2");
}
 
Example 7
Source File: TimestampTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test40() throws Exception {
    int nanos = 999999999;
    Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
    ts1.setNanos(nanos);
    assertTrue(ts1.getNanos() == nanos, "Error Invalid Nanos value");
}
 
Example 8
Source File: TimestampTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test05() throws Exception {
    String testTS = "2009-1-01 10:50:0";
    String ExpectedTS = "2009-01-01 10:50:0";
    Timestamp ts = Timestamp.valueOf(testTS);
    Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
    assertEquals(ts, ts2, "Error ts1 != ts2");
}
 
Example 9
Source File: DateTimeTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Regression test case for DERBY-4621, which caused the conversion of
 * timestamp and time values to varchar to generate wrong results when
 * a Calendar object was supplied.
 */
public void testConversionToString() throws SQLException {
    String timestampString = "2010-04-20 15:17:36.0";
    String timeString = "15:17:36";
    String dateString = "2010-04-20";

    Timestamp ts = Timestamp.valueOf(timestampString);
    Time t = Time.valueOf(timeString);
    Date d = Date.valueOf(dateString);

    PreparedStatement ps =
            prepareStatement("VALUES CAST(? AS VARCHAR(40))");

    ps.setTimestamp(1, ts);
    JDBC.assertSingleValueResultSet(ps.executeQuery(), timestampString);

    // Used to give wrong result - 2010-04-20 03:17:36
    ps.setTimestamp(1, ts, Calendar.getInstance());
    JDBC.assertSingleValueResultSet(ps.executeQuery(), timestampString);

    ps.setTime(1, t);
    JDBC.assertSingleValueResultSet(ps.executeQuery(), timeString);

    // Used to give wrong result - 03:17:36
    ps.setTime(1, t, Calendar.getInstance());
    JDBC.assertSingleValueResultSet(ps.executeQuery(), timeString);

    ps.setDate(1, d);
    JDBC.assertSingleValueResultSet(ps.executeQuery(), dateString);

    ps.setDate(1, d, Calendar.getInstance());
    JDBC.assertSingleValueResultSet(ps.executeQuery(), dateString);
}
 
Example 10
Source File: LocalDateConverter.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@Override
public Timestamp convertToDatabaseColumn(LocalDate value) {
	if (value != null) {
		return Timestamp.valueOf(value.atStartOfDay());
	}
	return null;
}
 
Example 11
Source File: ParamAndColumnHintTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public final void testFetchWithTimestampHint( )
    throws DataException
{
     String queryText = 
        "select acDate, acTimestamp from acdatatypes where acTimestamp > ? ";

    // If connection fails, fix connection properties
    m_statement = getLocalMySqlConnection( ).prepareStatement( queryText,
            JDBCOdaDataSource.DATA_SET_TYPE );

    ParameterHint hint = new ParameterHint( "param1", true, false );
    hint.setPosition( 1 );  // use param index below to match hints during retry
    hint.setDataType( java.util.Date.class );
    hint.setNativeDataType( Types.TIMESTAMP );
    m_statement.addParameterHint( hint );

    Timestamp ts = Timestamp.valueOf( "1999-12-31 03:13:00" );
    m_statement.setParameterValue( 1, ts );
    
    // since runtime metadata is available, hint is not used
    ColumnHint columnHint = new ColumnHint( "acTimestamp" );
    columnHint.setDataType( Integer.class );
    columnHint.setNativeDataType( Types.TIMESTAMP );
    m_statement.addColumnHint( columnHint );

    m_statement.execute( );       
    ResultSet resultSet = m_statement.getResultSet( );
    IResultObject resultObject = null;
    int numRows = 0;
    while ( ( resultObject = resultSet.fetch( ) ) != null )
    {
        numRows++;
        assertEquals( Timestamp.class,
                      resultObject.getResultClass( )
                            .getFieldValueClass( "acTimestamp" ));
        Object value = resultObject.getFieldValue( "acTimestamp" );
        assertTrue( value instanceof Timestamp );
    }
    assertEquals( 4, numRows );
}
 
Example 12
Source File: TimestampTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test35() {
    Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
    Timestamp ts2 = Timestamp.valueOf("1966-08-30 08:08:08");
    assertTrue(ts2.getTime() == ts1.getTime(),
            "ts1.getTime() != ts2.getTime()");
    assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
}
 
Example 13
Source File: TimestampTests.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test18() {
    Timestamp ts1 = Timestamp.valueOf("1999-11-10 12:26:19.3456543");
    assertFalse(ts1.before(ts1), "Error ts1 before ts1!");
}
 
Example 14
Source File: CalciteRemoteDriverTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
private Object convert(Object o, Class clazz) throws ParseException {
  if (o.getClass() == clazz) {
    return o;
  }
  if (clazz == String.class) {
    return o.toString();
  }
  if (clazz == Boolean.class) {
    return o instanceof Number
        && ((Number) o).intValue() != 0
        || o instanceof String
        && ((String) o).equalsIgnoreCase("true");
  }
  if (clazz == byte[].class) {
    if (o instanceof String) {
      return ((String) o).getBytes(StandardCharsets.UTF_8);
    }
  }
  if (clazz == Timestamp.class) {
    if (o instanceof String) {
      return Timestamp.valueOf((String) o);
    }
  }
  if (clazz == Time.class) {
    if (o instanceof String) {
      return Time.valueOf((String) o);
    }
  }
  if (clazz == java.sql.Date.class) {
    if (o instanceof String) {
      return java.sql.Date.valueOf((String) o);
    }
  }
  if (clazz == java.util.Date.class) {
    if (o instanceof String) {
      final DateFormat dateFormat =
          DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT,
              Locale.ROOT);
      return dateFormat.parse((String) o);
    }
  }
  if (clazz == Calendar.class) {
    if (o instanceof String) {
      return Util.calendar(); // TODO:
    }
  }
  if (o instanceof Boolean) {
    o = (Boolean) o ? 1 : 0;
  }
  if (o instanceof Number) {
    final Number number = (Number) o;
    if (Number.class.isAssignableFrom(clazz)) {
      if (clazz == BigDecimal.class) {
        if (o instanceof Double || o instanceof Float) {
          return new BigDecimal(number.doubleValue());
        } else {
          return new BigDecimal(number.longValue());
        }
      } else if (clazz == BigInteger.class) {
        return new BigInteger(o.toString());
      } else if (clazz == Byte.class || clazz == byte.class) {
        return number.byteValue();
      } else if (clazz == Short.class || clazz == short.class) {
        return number.shortValue();
      } else if (clazz == Integer.class || clazz == int.class) {
        return number.intValue();
      } else if (clazz == Long.class || clazz == long.class) {
        return number.longValue();
      } else if (clazz == Float.class || clazz == float.class) {
        return number.floatValue();
      } else if (clazz == Double.class || clazz == double.class) {
        return number.doubleValue();
      }
    }
  }
  if (Number.class.isAssignableFrom(clazz)) {
    if (clazz == BigDecimal.class) {
      return new BigDecimal(o.toString());
    } else if (clazz == BigInteger.class) {
      return new BigInteger(o.toString());
    } else if (clazz == Byte.class || clazz == byte.class) {
      return Byte.valueOf(o.toString());
    } else if (clazz == Short.class || clazz == short.class) {
      return Short.valueOf(o.toString());
    } else if (clazz == Integer.class || clazz == int.class) {
      return Integer.valueOf(o.toString());
    } else if (clazz == Long.class || clazz == long.class) {
      return Long.valueOf(o.toString());
    } else if (clazz == Float.class || clazz == float.class) {
      return Float.valueOf(o.toString());
    } else if (clazz == Double.class || clazz == double.class) {
      return Double.valueOf(o.toString());
    }
  }
  throw new AssertionError("cannot convert " + o + "(" + o.getClass()
      + ") to " + clazz);
}
 
Example 15
Source File: TimestampTests.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test12() {
    Timestamp ts1 = Timestamp.valueOf("1996-10-15 12:26:19.12");
    assertTrue(ts1.equals(ts1), "Error ts1 != ts1");
}
 
Example 16
Source File: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 4 votes vote down vote up
@Override
public String updateAgent(String agentId, String configDetails, String toolName, String agentVersion,
		String osversion, boolean vault) throws InsightsCustomException {
	try {
		if (!agentConfigDAL.isAgentIdExisting(agentId)) {
			throw new InsightsCustomException("No data found for agent id " + agentId);
		}
		// Get latest agent code
		String labelName = null;
		getToolRawConfigFile(agentVersion, toolName);
		setupAgentInstanceCreation(toolName, osversion, agentId);
		AgentConfigTO agentConfig = getAgentDetails(agentId);
		String oldVersion = agentConfig.getAgentVersion();
		log.debug("Previous Agent version {} ---", agentConfig.getAgentVersion());
		if (!oldVersion.equals(agentVersion)) {
			// Get latest agent code
			getToolRawConfigFile(agentVersion, toolName);
			setupAgentInstanceCreation(toolName, osversion, agentId);
		}
		Gson gson = new Gson();
		JsonElement jelement = gson.fromJson(configDetails.trim(), JsonElement.class);
		JsonObject json = jelement.getAsJsonObject();
		json.addProperty("osversion", osversion);
		json.addProperty("agentVersion", agentVersion);
		Date updateDate = Timestamp.valueOf(LocalDateTime.now());
		if (vault) {
			log.debug("--update Store secrets to vault --");
			HashMap<String, Map<String, String>> dataMap = getToolbasedSecret(json, agentId);
			updateSecrets(agentId, dataMap, json);
		}
		Path agentZipPath = updateAgentConfig(toolName, json, agentId);
		byte[] data = Files.readAllBytes(agentZipPath);
		String fileName = agentId + ZIPEXTENSION;
		sendAgentPackage(data, AGENTACTION.UPDATE.name(), fileName, agentId, toolName, osversion);
		labelName = this.getLabelName(configDetails);
		agentConfigDAL.updateAgentConfigFromUI(agentId, json.get("toolCategory").getAsString(), labelName, toolName,
				json, agentVersion, osversion, updateDate, vault);
		return SUCCESS;
	} catch (Exception e) {
		log.error("Error while updating agent", e);
		throw new InsightsCustomException(e.getMessage());
	}
}
 
Example 17
Source File: TimestampTests.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test25() {
    Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
    Timestamp ts2 = new Timestamp(ts1.getTime());
    assertTrue(ts1.compareTo(ts2) == 0, "Error ts1 != ts2");
}
 
Example 18
Source File: PutORCTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteORCWithAvroLogicalTypes() throws IOException, InitializationException {
    final String avroSchema = IOUtils.toString(new FileInputStream("src/test/resources/user_logical_types.avsc"), StandardCharsets.UTF_8);
    schema = new Schema.Parser().parse(avroSchema);
    LocalTime nowTime = LocalTime.now();
    LocalDateTime nowDateTime = LocalDateTime.now();
    LocalDate nowDate = LocalDate.now();

    final int timeMillis = nowTime.get(ChronoField.MILLI_OF_DAY);
    final Timestamp timestampMillis = Timestamp.valueOf(nowDateTime);
    final Date dt = Date.valueOf(nowDate);
    final BigDecimal bigDecimal = new BigDecimal("92.12");

    configure(proc, 10, (numUsers, readerFactory) -> {
        for (int i = 0; i < numUsers; i++) {
            readerFactory.addRecord(
                    i,
                    timeMillis,
                    timestampMillis,
                    dt,
                    bigDecimal);
        }
        return null;
    });

    final String filename = "testORCWithDefaults-" + System.currentTimeMillis();

    final Map<String, String> flowFileAttributes = new HashMap<>();
    flowFileAttributes.put(CoreAttributes.FILENAME.key(), filename);

    testRunner.setProperty(PutORC.HIVE_TABLE_NAME, "myTable");

    testRunner.enqueue("trigger", flowFileAttributes);
    testRunner.run();
    testRunner.assertAllFlowFilesTransferred(PutORC.REL_SUCCESS, 1);

    final Path orcFile = new Path(DIRECTORY + "/" + filename);

    // verify the successful flow file has the expected attributes
    final MockFlowFile mockFlowFile = testRunner.getFlowFilesForRelationship(PutORC.REL_SUCCESS).get(0);
    mockFlowFile.assertAttributeEquals(PutORC.ABSOLUTE_HDFS_PATH_ATTRIBUTE, orcFile.getParent().toString());
    mockFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), filename);
    mockFlowFile.assertAttributeEquals(PutORC.RECORD_COUNT_ATTR, "10");
    // DDL will be created with field names normalized (lowercased, e.g.) for Hive by default
    mockFlowFile.assertAttributeEquals(PutORC.HIVE_DDL_ATTRIBUTE,
            "CREATE EXTERNAL TABLE IF NOT EXISTS `myTable` (`id` INT, `timemillis` INT, `timestampmillis` TIMESTAMP, `dt` DATE, `dec` DECIMAL) STORED AS ORC");

    // verify we generated a provenance event
    final List<ProvenanceEventRecord> provEvents = testRunner.getProvenanceEvents();
    assertEquals(1, provEvents.size());

    // verify it was a SEND event with the correct URI
    final ProvenanceEventRecord provEvent = provEvents.get(0);
    assertEquals(ProvenanceEventType.SEND, provEvent.getEventType());
    // If it runs with a real HDFS, the protocol will be "hdfs://", but with a local filesystem, just assert the filename.
    Assert.assertTrue(provEvent.getTransitUri().endsWith(DIRECTORY + "/" + filename));

    // verify the content of the ORC file by reading it back in
    verifyORCUsers(orcFile, 10, (x, currUser) -> {
                assertEquals((int) currUser, ((IntWritable) x.get(0)).get());
                assertEquals(timeMillis, ((IntWritable) x.get(1)).get());
                assertEquals(timestampMillis, ((TimestampWritableV2) x.get(2)).getTimestamp().toSqlTimestamp());
                final DateFormat noTimeOfDayDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                noTimeOfDayDateFormat.setTimeZone(TimeZone.getTimeZone("gmt"));
                assertEquals(noTimeOfDayDateFormat.format(dt), ((DateWritableV2) x.get(3)).get().toString());
                assertEquals(bigDecimal, ((HiveDecimalWritable) x.get(4)).getHiveDecimal().bigDecimalValue());
                return null;
            }
    );

    // verify we don't have the temp dot file after success
    final File tempOrcFile = new File(DIRECTORY + "/." + filename);
    Assert.assertFalse(tempOrcFile.exists());

    // verify we DO have the CRC file after success
    final File crcAvroORCFile = new File(DIRECTORY + "/." + filename + ".crc");
    Assert.assertTrue(crcAvroORCFile.exists());
}
 
Example 19
Source File: TimestampTests.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test31() {
    Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
    Date d = new Date(ts1.getTime());
    assertFalse(ts1.equals(d), "Error ts1 != d");
}
 
Example 20
Source File: SqlTimestampParser.java    From flink with Apache License 2.0 3 votes vote down vote up
/**
 * Static utility to parse a field of type Timestamp from a byte sequence that represents text
 * characters
 * (such as when read from a file stream).
 *
 * @param bytes     The bytes containing the text data that should be parsed.
 * @param startPos  The offset to start the parsing.
 * @param length    The length of the byte sequence (counting from the offset).
 * @param delimiter The delimiter that terminates the field.
 * @return The parsed value.
 * @throws IllegalArgumentException Thrown when the value cannot be parsed because the text
 * represents not a correct number.
 */
public static final Timestamp parseField(byte[] bytes, int startPos, int length, char delimiter) {
	final int limitedLen = nextStringLength(bytes, startPos, length, delimiter);

	if (limitedLen > 0 &&
			(Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + limitedLen - 1]))) {
		throw new NumberFormatException("There is leading or trailing whitespace in the numeric field.");
	}

	final String str = new String(bytes, startPos, limitedLen, ConfigConstants.DEFAULT_CHARSET);
	return Timestamp.valueOf(str);
}