Java Code Examples for java.sql.Date#setTime()

The following examples show how to use java.sql.Date#setTime() . 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: Client.java    From Lottor with MIT License 6 votes vote down vote up
public static void deepCloneSerialize() throws Exception {
    Date date = new Date(12356565656L);
    SimpleObject p1 = new SimpleObject("原型对象", date);
    //通过序列化反序列化来新建一个对象
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(p1);
    byte[] bytes = bos.toByteArray();

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    SimpleObject p2 = (SimpleObject) ois.readObject();
    System.out.println(p1);
    System.out.println(p1.date);
    date.setTime(36565656562626L);
    System.out.println(p2);
    System.out.println(p2.date);
    System.out.println(p1.date);

}
 
Example 2
Source File: AccountRule.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method checks to see if the account expiration date is today's date or earlier
 *
 * @param newAccount
 * @return fails if the expiration date is null or after today's date
 */
protected boolean checkAccountExpirationDateValidTodayOrEarlier(Account newAccount) {

    // get today's date, with no time component
    Date todaysDate = new Date(getDateTimeService().getCurrentDate().getTime());
    todaysDate.setTime(DateUtils.truncate(todaysDate, Calendar.DAY_OF_MONTH).getTime());
    // TODO: convert this to using Wes' Kuali KfsDateUtils once we're using Date's instead of Timestamp

    // get the expiration date, if any
    Date expirationDate = newAccount.getAccountExpirationDate();
    if (ObjectUtils.isNull(expirationDate)) {
        putFieldError("accountExpirationDate", KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        return false;
    }

    // when closing an account, the account expiration date must be the current date or earlier
    expirationDate.setTime(DateUtils.truncate(expirationDate, Calendar.DAY_OF_MONTH).getTime());
    if (expirationDate.after(todaysDate)) {
        putFieldError("accountExpirationDate", KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        return false;
    }

    return true;
}
 
Example 3
Source File: SqlDateSerializer.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public Date copy(Date from, Date reuse) {
	if (from == null) {
		return null;
	}
	reuse.setTime(from.getTime());
	return reuse;
}
 
Example 4
Source File: SqlDateSerializer.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public Date deserialize(Date reuse, DataInputView source) throws IOException {
	final long v = source.readLong();
	if (v == Long.MIN_VALUE) {
		return null;
	}
	reuse.setTime(v);
	return reuse;
}
 
Example 5
Source File: SqlDateSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public Date copy(Date from, Date reuse) {
	if (from == null) {
		return null;
	}
	reuse.setTime(from.getTime());
	return reuse;
}
 
Example 6
Source File: SqlDateSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public Date deserialize(Date reuse, DataInputView source) throws IOException {
	final long v = source.readLong();
	if (v == Long.MIN_VALUE) {
		return null;
	}
	reuse.setTime(v);
	return reuse;
}
 
Example 7
Source File: Client.java    From Lottor with MIT License 5 votes vote down vote up
public static void shallowClone() throws Exception {
    Date date = new Date(12356565656L);
    SimpleObject p1 = new SimpleObject("原型对象", date);
    SimpleObject p2 = (SimpleObject) p1.clone();
    System.out.println(p1);
    System.out.println(p1.date);

    date.setTime(36565656562626L);
    System.out.println(p2);
    System.out.println(p2.date);
    System.out.println(p1.date);
}
 
Example 8
Source File: Client.java    From Lottor with MIT License 5 votes vote down vote up
public static void deepClone() throws Exception {
    Date date = new Date(12356565656L);
    SimpleObject p1 = new SimpleObject("原型对象", date);
    SimpleObject p2 = (SimpleObject) p1.deepClone();
    System.out.println(p1);
    System.out.println(p1.date);
    date.setTime(36565656562626L);
    System.out.println(p2);
    System.out.println(p2.date);
    System.out.println(p1.date);

}
 
Example 9
Source File: AccountRuleTest.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
public void testGuidelinesConditionallyRequired_TodaysDate() {

        boolean result;
        Account account = new Account();
        MaintenanceDocument maintDoc = newMaintDoc(account);
        AccountRule rule = (AccountRule) setupMaintDocRule(maintDoc, AccountRule.class);

        // setup a var with today's date
        Date today = new Date(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime());
        today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
        account.setAccountExpirationDate(today);
        result = rule.areGuidelinesRequired(account);
        assertEquals("Guidelines should be required for Account expiring today.", true, result);

    }
 
Example 10
Source File: DateSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public Date copy(Date from, Date reuse) {
	if (from == null) {
		return null;
	}
	reuse.setTime(from.getTime());
	return reuse;
}
 
Example 11
Source File: SqlDateSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public Date copy(Date from, Date reuse) {
	if (from == null) {
		return null;
	}
	reuse.setTime(from.getTime());
	return reuse;
}
 
Example 12
Source File: SqlDateSerializer.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public Date deserialize(Date reuse, DataInputView source) throws IOException {
	final long v = source.readLong();
	if (v == Long.MIN_VALUE) {
		return null;
	}
	reuse.setTime(v);
	return reuse;
}
 
Example 13
Source File: Datatypes.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static synchronized void add_one_row(Connection conn, int thread_id)
throws Exception {
	try {
		//initialize();
		PreparedStatement ps = conn.prepareStatement(
				" insert into Datatypes (id,t_char,t_blob," + "t_clob,"
				+ " t_date, t_decimal, t_decimal_nn, t_double, "
				+ " t_float, t_int, t_longint, t_numeric_large,"
				+ " t_real, t_smallint, t_time, t_timestamp,"
				+ " t_varchar) values ("
				+ " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)" 
				/* autoincrement feature added, so we need to specify the
				 * column name for prepared statement, otherwise auto increment
				 * column will think it is trying to update/insert a null value
				 * to the column.
				 */
				, Statement.RETURN_GENERATED_KEYS);
		InputStream streamIn = null;
		Reader streamReader = null;
		int ind = Rn.nextInt();
		double x;
		Date dt = new Date(1);
		Time tt = new Time(1);
		Timestamp ts = new Timestamp(1);
		String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV !@#$!@#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
		ps.setInt(1, ind);
		// scramble the string
		int i1 = Math.abs(ind % 100);
		String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
		int i2 = i1 < 89 ? i1 + 10 : i1;
		ps.setString(2, cs2.substring(0, i2));
		//"t_blob"
		int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamIn = new LoopingAlphabetStream(blobLength);
		ps.setBinaryStream(3, streamIn, blobLength);
		//"t_clob
		int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet
				.modernLatinLowercase());
		ps.setCharacterStream(4, streamReader, clobLength);
		//"t_ndate"
		dt.setTime(Math.abs(Rn.nextLong() / 150000));
		ps.setDate(5, dt);
		//"t_decimal"
		x = Math.abs(Rn.nextInt() % 18);
		if (x > 5)
			x = 5;
		ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_decimal_nn"
		ps.setDouble(7, Rn.nextDouble());
		//"t_double"
		ps.setDouble(8, Rn.nextDouble()
				* Math.pow(10, Math.abs(Rn.nextInt() % 300)));
		//"t_float"
		ps.setFloat(9, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
		//"t_int"
		ps.setInt(10, Rn.nextInt());
		//"t_longint"
		ps.setLong(11, Rn.nextLong());
		//"t_numeric_large"
		x = Math.abs(Rn.nextInt() % 30);
		if (x > 30)
			x = 31;
		ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_real"
		ps.setFloat(13, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
		//"t_smallint"
		ps.setInt(14, Rn.nextInt() % (256 * 128));
		//"t_time"
		tt.setTime(Math.abs(Rn.nextInt()));
		ps.setTime(15, tt);
		//"t_timestamp"
		ts.setTime(Math.abs(Rn.nextLong() / 50000));
		ps.setTimestamp(16, ts);
		//"t_varchar"
		ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
		int rows = ps.executeUpdate();
		if (rows == 1) {

			ResultSet rs = ps.getGeneratedKeys();

			while (rs.next()) {
				ResultSetMetaData rsmd = rs.getMetaData();
				int numCols = rsmd.getColumnCount();
			}
		} else
			System.out.println("t" + thread_id + " insert failed");
		streamReader.close();
		streamIn.close();

	} catch (SQLException se) {
		if (se.getNextException() == null)
			throw se;
		String m = se.getNextException().getSQLState();
		System.out.println(se.getNextException().getMessage()
				+ " SQLSTATE: " + m);
	}
}
 
Example 14
Source File: OrcTester.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
private static Object preprocessWriteValueOld(TypeInfo typeInfo, Object value) throws IOException
    {
        if (value == null) {
            return null;
        }
        switch (typeInfo.getCategory()) {
            case PRIMITIVE:
                PrimitiveObjectInspector.PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();
                switch (primitiveCategory) {
                    case BOOLEAN:
                        return value;
                    case BYTE:
                        return ((Number) value).byteValue();
                    case SHORT:
                        return ((Number) value).shortValue();
                    case INT:
                        return ((Number) value).intValue();
                    case LONG:
                        return ((Number) value).longValue();
                    case FLOAT:
                        return ((Number) value).floatValue();
                    case DOUBLE:
                        return ((Number) value).doubleValue();
                    case DECIMAL:
                        return HiveDecimal.create(((Decimal) value).toBigDecimal().bigDecimal());
                    case STRING:
                        return value;
                    case CHAR:
                        return new HiveChar(value.toString(), ((CharTypeInfo) typeInfo).getLength());
                    case DATE:
                        LocalDate localDate = LocalDate.ofEpochDay((int)value);
                        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

                        long millis = zonedDateTime.toEpochSecond() * 1000;
                        Date date = new Date(0);
                        // mills must be set separately to avoid masking
                        date.setTime(millis);
                        return date;
                    case TIMESTAMP:
                        long millisUtc = ((Long)value).intValue();
                        return new Timestamp(millisUtc);
                    case BINARY:
                        return ((String) value).getBytes();
//                        return (byte[])value;
                }
                break;
            case MAP:
                MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo;
                TypeInfo keyTypeInfo = mapTypeInfo.getMapKeyTypeInfo();
                TypeInfo valueTypeInfo = mapTypeInfo.getMapValueTypeInfo();
                Map<Object, Object> newMap = new HashMap<>();
                for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
                    newMap.put(preprocessWriteValueOld(keyTypeInfo, entry.getKey()), preprocessWriteValueOld(valueTypeInfo, entry.getValue()));
                }
                return newMap;
            case LIST:
                ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;
                TypeInfo elementTypeInfo = listTypeInfo.getListElementTypeInfo();
                List<Object> newList = new ArrayList<>(((Collection<?>) value).size());
                for (Object element : (Iterable<?>) value) {
                    newList.add(preprocessWriteValueOld(elementTypeInfo, element));
                }
                return newList;
            case STRUCT:
                StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;
                List<?> fieldValues = (List<?>) value;
                List<TypeInfo> fieldTypeInfos = structTypeInfo.getAllStructFieldTypeInfos();
                List<Object> newStruct = new ArrayList<>();
                for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
                    newStruct.add(preprocessWriteValueOld(fieldTypeInfos.get(fieldId), fieldValues.get(fieldId)));
                }
                return newStruct;
        }
        throw new IOException(format("Unsupported Hive type: %s", typeInfo));
    }
 
Example 15
Source File: Datatypes.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
public static synchronized void add_one_row(Connection conn, int thread_id)
throws Exception {
	try {
		//initialize();
		PreparedStatement ps = conn.prepareStatement(
				" insert into Datatypes (id,t_char,t_blob," + "t_clob,"
				+ " t_date, t_decimal, t_decimal_nn, t_double, "
				+ " t_float, t_int, t_longint, t_numeric_large,"
				+ " t_real, t_smallint, t_time, t_timestamp,"
				+ " t_varchar) values ("
				+ " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)" 
				/* autoincrement feature added, so we need to specify the
				 * column name for prepared statement, otherwise auto increment
				 * column will think it is trying to update/insert a null value
				 * to the column.
				 */
				, Statement.RETURN_GENERATED_KEYS);
		InputStream streamIn = null;
		Reader streamReader = null;
		int ind = Rn.nextInt();
		double x;
		Date dt = new Date(1);
		Time tt = new Time(1);
		Timestamp ts = new Timestamp(1);
		String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV !@#$!@#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
		ps.setInt(1, ind);
		// scramble the string
		int i1 = Math.abs(ind % 100);
		String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
		int i2 = i1 < 89 ? i1 + 10 : i1;
		ps.setString(2, cs2.substring(0, i2));
		//"t_blob"
		int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamIn = new LoopingAlphabetStream(blobLength);
		ps.setBinaryStream(3, streamIn, blobLength);
		//"t_clob
		int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet
				.modernLatinLowercase());
		ps.setCharacterStream(4, streamReader, clobLength);
		//"t_ndate"
		dt.setTime(Math.abs(Rn.nextLong() / 150000));
		ps.setDate(5, dt);
		//"t_decimal"
		x = Math.abs(Rn.nextInt() % 18);
		if (x > 5)
			x = 5;
		ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_decimal_nn"
		ps.setDouble(7, Rn.nextDouble());
		//"t_double"
		ps.setDouble(8, Rn.nextDouble()
				* Math.pow(10, Math.abs(Rn.nextInt() % 300)));
		//"t_float"
		ps.setFloat(9, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
		//"t_int"
		ps.setInt(10, Rn.nextInt());
		//"t_longint"
		ps.setLong(11, Rn.nextLong());
		//"t_numeric_large"
		x = Math.abs(Rn.nextInt() % 30);
		if (x > 30)
			x = 31;
		ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_real"
		ps.setFloat(13, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
		//"t_smallint"
		ps.setInt(14, Rn.nextInt() % (256 * 128));
		//"t_time"
		tt.setTime(Math.abs(Rn.nextInt()));
		ps.setTime(15, tt);
		//"t_timestamp"
		ts.setTime(Math.abs(Rn.nextLong() / 50000));
		ps.setTimestamp(16, ts);
		//"t_varchar"
		ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
		int rows = ps.executeUpdate();
		if (rows == 1) {

			ResultSet rs = ps.getGeneratedKeys();

			while (rs.next()) {
				ResultSetMetaData rsmd = rs.getMetaData();
				int numCols = rsmd.getColumnCount();
			}
		} else
			System.out.println("t" + thread_id + " insert failed");
		streamReader.close();
		streamIn.close();

	} catch (SQLException se) {
		if (se.getNextException() == null)
			throw se;
		String m = se.getNextException().getSQLState();
		System.out.println(se.getNextException().getMessage()
				+ " SQLSTATE: " + m);
	}
}
 
Example 16
Source File: Datatypes.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static synchronized void add_one_row(Connection conn, int thread_id)
throws Exception {
	try {
		//initialize();
		PreparedStatement ps = conn.prepareStatement(
				" insert into Datatypes (id,t_char,t_blob," + "t_clob,"
				+ " t_date, t_decimal, t_decimal_nn, t_double, "
				+ " t_float, t_int, t_longint, t_numeric_large,"
				+ " t_real, t_smallint, t_time, t_timestamp,"
				+ " t_varchar) values ("
				+ " ?,?, ?,?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?,?)" 
				/* autoincrement feature added, so we need to specify the
				 * column name for prepared statement, otherwise auto increment
				 * column will think it is trying to update/insert a null value
				 * to the column.
				 */
				, Statement.RETURN_GENERATED_KEYS);
		InputStream streamIn = null;
		Reader streamReader = null;
		int ind = Rn.nextInt();
		double x;
		Date dt = new Date(1);
		Time tt = new Time(1);
		Timestamp ts = new Timestamp(1);
		String cs = "asdf qwerqwer 12341234 ZXCVZXCVZXCV !@#$!@#$ asdfasdf 1 q a z asdf ASDF qwerasdfzxcvasdfqwer1234asd#";
		ps.setInt(1, ind);
		// scramble the string
		int i1 = Math.abs(ind % 100);
		String cs2 = cs.substring(i1, 99) + cs.substring(0, i1);
		int i2 = i1 < 89 ? i1 + 10 : i1;
		ps.setString(2, cs2.substring(0, i2));
		//"t_blob"
		int blobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamIn = new LoopingAlphabetStream(blobLength);
		ps.setBinaryStream(3, streamIn, blobLength);
		//"t_clob
		int clobLength = Rn.nextInt(102400 - 0 + 1) + 0;//to create a stream of random length between 0 and 100K
		streamReader = new LoopingAlphabetReader(clobLength, CharAlphabet
				.modernLatinLowercase());
		ps.setCharacterStream(4, streamReader, clobLength);
		//"t_ndate"
		dt.setTime(Math.abs(Rn.nextLong() / 150000));
		ps.setDate(5, dt);
		//"t_decimal"
		x = Math.abs(Rn.nextInt() % 18);
		if (x > 5)
			x = 5;
		ps.setDouble(6, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_decimal_nn"
		ps.setDouble(7, Rn.nextDouble());
		//"t_double"
		ps.setDouble(8, Rn.nextDouble()
				* Math.pow(10, Math.abs(Rn.nextInt() % 300)));
		//"t_float"
		ps.setFloat(9, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 30)));
		//"t_int"
		ps.setInt(10, Rn.nextInt());
		//"t_longint"
		ps.setLong(11, Rn.nextLong());
		//"t_numeric_large"
		x = Math.abs(Rn.nextInt() % 30);
		if (x > 30)
			x = 31;
		ps.setDouble(12, Math.abs(Rn.nextDouble() * Math.pow(10, x)));
		//"t_real"
		ps.setFloat(13, Rn.nextFloat()
				* (float) Math.pow(10, Math.abs(Rn.nextInt() % 7)));
		//"t_smallint"
		ps.setInt(14, Rn.nextInt() % (256 * 128));
		//"t_time"
		tt.setTime(Math.abs(Rn.nextInt()));
		ps.setTime(15, tt);
		//"t_timestamp"
		ts.setTime(Math.abs(Rn.nextLong() / 50000));
		ps.setTimestamp(16, ts);
		//"t_varchar"
		ps.setString(17, cs.substring(Math.abs(Rn.nextInt() % 100)));
		int rows = ps.executeUpdate();
		if (rows == 1) {

			ResultSet rs = ps.getGeneratedKeys();

			while (rs.next()) {
				ResultSetMetaData rsmd = rs.getMetaData();
				int numCols = rsmd.getColumnCount();
			}
		} else
			System.out.println("t" + thread_id + " insert failed");
		streamReader.close();
		streamIn.close();

	} catch (SQLException se) {
		if (se.getNextException() == null)
			throw se;
		String m = se.getNextException().getSQLState();
		System.out.println(se.getNextException().getMessage()
				+ " SQLSTATE: " + m);
	}
}
 
Example 17
Source File: OrcTester.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Object preprocessWriteValueHive(Type type, Object value)
{
    if (value == null) {
        return null;
    }

    if (type.equals(BOOLEAN)) {
        return value;
    }
    if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    }
    if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    }
    if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    }
    if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    }
    if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    }
    if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    if (type instanceof VarcharType) {
        return value;
    }
    if (type instanceof CharType) {
        return new HiveChar((String) value, ((CharType) type).getLength());
    }
    if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    }
    if (type.equals(DATE)) {
        int days = ((SqlDate) value).getDays();
        LocalDate localDate = LocalDate.ofEpochDay(days);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        long millis = SECONDS.toMillis(zonedDateTime.toEpochSecond());
        Date date = new Date(0);
        // millis must be set separately to avoid masking
        date.setTime(millis);
        return date;
    }
    if (type.equals(TIMESTAMP)) {
        long millisUtc = ((SqlTimestamp) value).getMillisUtc();
        return new Timestamp(millisUtc);
    }
    if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    }
    if (type instanceof ArrayType) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream()
                .map(element -> preprocessWriteValueHive(elementType, element))
                .collect(toList());
    }
    if (type instanceof MapType) {
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueHive(keyType, entry.getKey()), preprocessWriteValueHive(valueType, entry.getValue()));
        }
        return newMap;
    }
    if (type instanceof RowType) {
        List<?> fieldValues = (List<?>) value;
        List<Type> fieldTypes = type.getTypeParameters();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueHive(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
 
Example 18
Source File: RcFileTester.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Object preprocessWriteValueOld(Type type, Object value)
{
    if (value == null) {
        return null;
    }

    if (type.equals(BOOLEAN)) {
        return value;
    }
    if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    }
    if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    }
    if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    }
    if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    }
    if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    }
    if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    if (type instanceof VarcharType) {
        return value;
    }
    if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    }
    if (type.equals(DATE)) {
        int days = ((SqlDate) value).getDays();
        LocalDate localDate = LocalDate.ofEpochDay(days);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        long millis = zonedDateTime.toEpochSecond() * 1000;
        Date date = new Date(0);
        // mills must be set separately to avoid masking
        date.setTime(millis);
        return date;
    }
    if (type.equals(TIMESTAMP)) {
        long millisUtc = (int) ((SqlTimestamp) value).getMillisUtc();
        return new Timestamp(millisUtc);
    }
    if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    }
    if (type instanceof ArrayType) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream()
                .map(element -> preprocessWriteValueOld(elementType, element))
                .collect(toList());
    }
    if (type instanceof MapType) {
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueOld(keyType, entry.getKey()), preprocessWriteValueOld(valueType, entry.getValue()));
        }
        return newMap;
    }
    if (type instanceof RowType) {
        List<?> fieldValues = (List<?>) value;
        List<Type> fieldTypes = type.getTypeParameters();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueOld(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}