Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java.sql.Time & java.sql.Date #219

Merged
merged 9 commits into from
Aug 30, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 230 additions & 0 deletions java_sql_time.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package hessian

import (
"io"
"reflect"
"time"
)

import (
perrors "github.com/pkg/errors"
)

func init() {
RegisterPOJO(&Date{})
RegisterPOJO(&Time{})
}

type JavaSqlTime interface {
ValueOf(timeStr string) error
setTime(time time.Time)
JavaClassName() string
time() time.Time
}

type Date struct {
time.Time
}

func (d *Date) time() time.Time {
return d.Time
}

func (d *Date) setTime(time time.Time) {
d.Time = time
}

zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
func (Date) JavaClassName() string {
return "java.sql.Date"
}

func (d *Date) ValueOf(dateStr string) error {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
time, err := time.Parse("2006-01-02", dateStr)
if err != nil {
return err
}
d.Time = time
return nil
}

func (d *Date) Year() int {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return d.Time.Year()
}

func (d *Date) Month() time.Month {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return d.Time.Month()
}

func (d *Date) Day() int {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return d.Time.Day()
}

type Time struct {
time.Time
}

func (Time) JavaClassName() string {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return "java.sql.Time"
}

func (t Time) time() time.Time {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return t.Time
}

func (t *Time) Hours() int {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return t.Time.Hour()
}

func (t *Time) Minutes() int {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return t.Time.Minute()
}

func (t *Time) Seconds() int {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
return t.Time.Second()
}

func (t *Time) setTime(time time.Time) {
t.Time = time
}

func (t *Time) ValueOf(timeStr string) error {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
time, err := time.Parse("15:04:05", timeStr)
if err != nil {
return err
}
t.Time = time
return nil
}

var javaSqlTimeTypeMap = make(map[string]reflect.Type, 16)
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved

func SetJavaSqlTimeSerialize(time JavaSqlTime) {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
name := time.JavaClassName()
var typ = reflect.TypeOf(time)
SetSerializer(name, JavaSqlTimeSerializer{})
//RegisterPOJO(time)
javaSqlTimeTypeMap[name] = typ
}

func getJavaSqlTimeSerialize(name string) reflect.Type {
return javaSqlTimeTypeMap[name]
}

type JavaSqlTimeSerializer struct {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
wongoo marked this conversation as resolved.
Show resolved Hide resolved
}

func (JavaSqlTimeSerializer) EncObject(e *Encoder, vv POJO) error {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved

var (
idx int
idx1 int
i int
err error
clsDef classInfo
)
v, ok := vv.(JavaSqlTime)
if !ok {
return perrors.New("can not be converted into java sql time object")
}
className := v.JavaClassName()
if className == "" {
return perrors.New("class name empty")
}

tValue := reflect.ValueOf(vv)
// check ref
if n, ok := e.checkRefMap(tValue); ok {
e.buffer = encRef(e.buffer, n)
return nil
}

// write object definition
idx = -1
for i = range e.classInfoList {
if v.JavaClassName() == e.classInfoList[i].javaName {
idx = i
break
}
}

if idx == -1 {
idx1, ok = checkPOJORegistry(typeof(v))
if !ok {
if reflect.TypeOf(v).Implements(javaEnumType) {
idx1 = RegisterJavaEnum(v.(POJOEnum))
} else {
idx1 = RegisterPOJO(v)
}
}
_, clsDef, err = getStructDefByIndex(idx1)
if err != nil {
return perrors.WithStack(err)
}

i = len(e.classInfoList)
e.classInfoList = append(e.classInfoList, clsDef)
e.buffer = append(e.buffer, clsDef.buffer...)
e.buffer = e.buffer[0 : len(e.buffer)-1]
}

if idx == -1 {
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
e.buffer = encInt32(e.buffer, 1)
e.buffer = encString(e.buffer, "value")

// write object instance
if byte(i) <= OBJECT_DIRECT_MAX {
e.buffer = encByte(e.buffer, byte(i)+BC_OBJECT_DIRECT)
} else {
e.buffer = encByte(e.buffer, BC_OBJECT)
e.buffer = encInt32(e.buffer, int32(idx1))
}
e.buffer = encDateInMs(e.buffer, v.time())
}

return nil
}

func (JavaSqlTimeSerializer) DecObject(d *Decoder, typ reflect.Type, cls classInfo) (interface{}, error) {

if typ.Kind() != reflect.Struct {
return nil, perrors.Errorf("wrong type expect Struct but get:%s", typ.String())
}

vRef := reflect.New(typ)
// add pointer ref so that ref the same object
d.appendRefs(vRef.Interface())

tag, err := d.readByte()
if err == io.EOF {
return nil, err
}
date, err := d.decDate(int32(tag))
if err != nil {
date = date
}
sqlTime := vRef.Interface()

result, ok := sqlTime.(JavaSqlTime)
result.setTime(date)
if !ok {
panic("result type is not sql time, please check the whether the conversion is ok")
}
return result, nil
}
97 changes: 97 additions & 0 deletions java_sql_time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package hessian

import (
"github.com/stretchr/testify/assert"
zhangshen023 marked this conversation as resolved.
Show resolved Hide resolved
"testing"
"time"
)

func init() {
SetJavaSqlTimeSerialize(&Date{})
SetJavaSqlTimeSerialize(&Time{})
}

// test local time between go and java
// go encode
// java decode
func TestJavaSqlTimeEncode(t *testing.T) {
sqlTime := time.Date(1997, 1, 1, 13, 15, 46, 0, time.UTC)
testSqlTime := Time{Time: sqlTime}
testJavaDecode(t, "javaSql_encode_time", &testSqlTime)

sqlDate := time.Date(2020, 8, 9, 0, 0, 0, 0, time.UTC)
testSqlDate := Date{Time: sqlDate}
testJavaDecode(t, "javaSql_encode_date", &testSqlDate)
}

// test local time between go and java
// java encode
// go decode
func TestJavaSqlTimeDecode(t *testing.T) {
sqlTime := time.Date(1997, 1, 1, 13, 15, 46, 0, time.UTC)
testSqlTime := Time{Time: sqlTime}
testDecodeJavaSqlTime(t, "javaSql_decode_time", &testSqlTime)

sqlDate := time.Date(2020, 8, 9, 0, 0, 0, 0, time.UTC)
testDateTime := Date{Time: sqlDate}
testDecodeJavaSqlTime(t, "javaSql_decode_date", &testDateTime)
}

func testDecodeJavaSqlTime(t *testing.T, method string, expected JavaSqlTime) {
r, e := decodeJavaResponse(method, "", false)
if e != nil {
t.Errorf("%s: decode fail with error %v", method, e)
return
}

resultSqlTime, ok := r.(JavaSqlTime)

if !ok {
t.Errorf("got error type:%v", r)
}
assert.Equal(t, resultSqlTime.time().UnixNano(), expected.time().UnixNano())
}

// test local time between go and go
// go encode
// go decode
func TestJavaSqlTimeWithGo(t *testing.T) {
location, _ := time.ParseInLocation("2006-01-02 15:04:05", "1997-01-01 13:15:46", time.Local)
sqlTime := Time{Time: location}
e := NewEncoder()
e.Encode(&sqlTime)
if len(e.Buffer()) == 0 {
t.Fail()
}
d := NewDecoder(e.Buffer())
resultSqlTime, _ := d.Decode()
assert.Equal(t, &sqlTime, resultSqlTime)

location, _ = time.ParseInLocation("2006-01-02 15:04:05", "2020-08-09 00:00:00", time.Local)
sqlDate := Date{Time: location}
e = NewEncoder()
e.Encode(&sqlDate)
if len(e.Buffer()) == 0 {
t.Fail()
}
d = NewDecoder(e.Buffer())
resultSqlDate, _ := d.Decode()
assert.Equal(t, &sqlDate, resultSqlDate)
}
23 changes: 21 additions & 2 deletions test_hessian/src/main/java/test/Hessian.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,34 @@ public static void main(String[] args) throws Exception {
Hessian2Output output = new Hessian2Output(System.out);
output.writeObject(object);
output.flush();
}else if(args[0].startsWith("java8_")){
} else if (args[0].startsWith("java8_")) {
//add java8 java.time Object test
Method method = TestJava8Time.class.getMethod(args[0]);
Object obj = new Object();
Object object =method.invoke(obj);
Object object = method.invoke(obj);

Hessian2Output output = new Hessian2Output(System.out);
output.writeObject(object);
output.flush();
} else if (args[0].startsWith("javaSql_")) {
if (args[0].startsWith("javaSql_encode")) {

Hessian2Input input = new Hessian2Input(System.in);
Object o = input.readObject();

Method method = TestJavaSqlTime.class.getMethod(args[0], Object.class);
TestJavaSqlTime testJavaSqlTime = new TestJavaSqlTime();
System.out.print(method.invoke(testJavaSqlTime, o));
} else {
Method method = TestJavaSqlTime.class.getMethod(args[0]);
TestJavaSqlTime testJavaSqlTime = new TestJavaSqlTime();
Object object = method.invoke(testJavaSqlTime);

Hessian2Output output = new Hessian2Output(System.out);
output.writeObject(object);
output.flush();
}

}
}

Expand Down
Loading