Elffuss BraidHub

kikocis/java-driver public

JAVA-606: Codec support for Java 8.

This commit introduces new codecs to automatically map Java 8 Date & Time API types such
as LocalTime, LocalDate, Instant and ZonedDateTime to CQL types (respectively, time, date,
timestamp and tuple<timestamp,varchar>).

It also introduces a new codec to support Java 8 Optional API.
Changeset8896a4ec25889b1b80c334cc1116354996d00dc0e57d0c86a93e6d72040dc2cc
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-10-27 09:42 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-17 14:51 +01:00
Parents12354430b10c

Browse the files at this changeset

13 files changed

modified changelog/README.md +1 −0
@@ -16,6 +16,7 @@
1616 - [improvement] JAVA-936: Adapt schema metadata parsing logic to new storage format of CQL types in C* 3.0.
1717 - [new feature] JAVA-846: Provide custom codecs library as an extra module.
1818 - [new feature] JAVA-742: Codec Support for JSON.
19+- [new feature] JAVA-606: Codec support for Java 8.
1920
2021 Merged from 2.1 branch:
2122
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/InstantCodec.java +135 −0
@@ -0,0 +1,135 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.Instant;
20+import java.time.format.DateTimeFormatter;
21+import java.time.format.DateTimeFormatterBuilder;
22+import java.time.format.DateTimeParseException;
23+import java.util.Date;
24+
25+import static java.lang.Long.parseLong;
26+import static java.time.Instant.ofEpochMilli;
27+import static java.time.ZoneOffset.UTC;
28+import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29+import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30+import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31+import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32+
33+import com.datastax.driver.core.DataType;
34+import com.datastax.driver.core.ProtocolVersion;
35+import com.datastax.driver.core.TypeCodec;
36+import com.datastax.driver.core.exceptions.InvalidTypeException;
37+
38+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
39+import static com.datastax.driver.core.ParseUtils.isQuoted;
40+import static com.datastax.driver.core.ParseUtils.quote;
41+import static com.datastax.driver.core.ParseUtils.unquote;
42+
43+/**
44+ * <p>
45+ * {@link TypeCodec} that maps {@link Instant} <-> {@link Date}
46+ * allowing the setting and retrieval of <code>timestamp</code>
47+ * columns as {@link Instant} instances.
48+ * </p>
49+ *
50+ * <p>
51+ * Since C* <code>timestamp</code> columns do not preserve timezones
52+ * any attached timezone information will be lost.
53+ * </p>
54+ *
55+ * @see ZonedDateTimeCodec
56+ * @see "https://cassandra.apache.org/doc/cql3/CQL-2.2.html#usingtimestamps"
57+ */
58+public class InstantCodec extends TypeCodec<Instant> {
59+
60+ public static final InstantCodec instance = new InstantCodec();
61+
62+ /**
63+ * A {@link DateTimeFormatter} that parses (most) of
64+ * the ISO formats accepted in CQL.
65+ */
66+ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
67+ .parseCaseSensitive()
68+ .parseStrict()
69+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
70+ .optionalStart()
71+ .appendLiteral('T')
72+ .appendValue(HOUR_OF_DAY, 2)
73+ .appendLiteral(':')
74+ .appendValue(MINUTE_OF_HOUR, 2)
75+ .optionalEnd()
76+ .optionalStart()
77+ .appendLiteral(':')
78+ .appendValue(SECOND_OF_MINUTE, 2)
79+ .optionalEnd()
80+ .optionalStart()
81+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
82+ .optionalEnd()
83+ .optionalStart()
84+ .appendZoneId()
85+ .optionalEnd()
86+ .toFormatter()
87+ .withZone(UTC);
88+
89+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
90+ .withZone(UTC);
91+
92+
93+ private InstantCodec() {
94+ super(DataType.timestamp(), Instant.class);
95+ }
96+
97+ @Override
98+ public ByteBuffer serialize(Instant value, ProtocolVersion protocolVersion) {
99+ return value == null ? null : bigint().serializeNoBoxing(value.toEpochMilli(), protocolVersion);
100+ }
101+
102+ @Override
103+ public Instant deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
104+ return bytes == null || bytes.remaining() == 0 ? null : ofEpochMilli(bigint().deserializeNoBoxing(bytes, protocolVersion));
105+ }
106+
107+ @Override
108+ public String format(Instant value) {
109+ if (value == null)
110+ return "NULL";
111+ return quote(FORMATTER.format(value));
112+ }
113+
114+ @Override
115+ public Instant parse(String value) {
116+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
117+ return null;
118+ // strip enclosing single quotes, if any
119+ if (isQuoted(value))
120+ value = unquote(value);
121+ if (isLongLiteral(value)) {
122+ try {
123+ return ofEpochMilli(parseLong(value));
124+ } catch (NumberFormatException e) {
125+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
126+ }
127+ }
128+ try {
129+ return Instant.from(PARSER.parse(value));
130+ } catch (DateTimeParseException e) {
131+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", value));
132+ }
133+ }
134+
135+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodec.java +108 −0
@@ -0,0 +1,108 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.LocalDate;
20+import java.time.temporal.ChronoUnit;
21+
22+import static java.lang.Long.parseLong;
23+import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
24+
25+import com.datastax.driver.core.*;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+import static com.datastax.driver.core.CodecUtils.fromCqlDateToDaysSinceEpoch;
29+import static com.datastax.driver.core.CodecUtils.fromSignedToUnsignedInt;
30+import static com.datastax.driver.core.CodecUtils.fromUnsignedToSignedInt;
31+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
32+import static com.datastax.driver.core.ParseUtils.isQuoted;
33+import static com.datastax.driver.core.ParseUtils.quote;
34+import static com.datastax.driver.core.ParseUtils.unquote;
35+
36+/**
37+ * {@link TypeCodec} that maps
38+ * {@link java.time.LocalDate} to CQL <code>date</code> columns.
39+ */
40+public class LocalDateCodec extends TypeCodec<LocalDate> {
41+
42+ public static final LocalDateCodec instance = new LocalDateCodec();
43+
44+ private static final LocalDate EPOCH = LocalDate.of(1970, 1, 1);
45+
46+ private LocalDateCodec() {
47+ super(DataType.date(), LocalDate.class);
48+ }
49+
50+ @Override
51+ public ByteBuffer serialize(LocalDate value, ProtocolVersion protocolVersion) {
52+ if (value == null)
53+ return null;
54+ long days = ChronoUnit.DAYS.between(EPOCH, value);
55+ int unsigned = fromSignedToUnsignedInt((int) days);
56+ return cint().serializeNoBoxing(unsigned, protocolVersion);
57+ }
58+
59+ @Override
60+ public LocalDate deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) {
61+ if (bytes == null || bytes.remaining() == 0)
62+ return null;
63+ int unsigned = cint().deserializeNoBoxing(bytes, protocolVersion);
64+ int signed = fromUnsignedToSignedInt(unsigned);
65+ return EPOCH.plusDays(signed);
66+ }
67+
68+ @Override
69+ public String format(LocalDate value) {
70+ if (value == null)
71+ return "NULL";
72+ return quote(ISO_LOCAL_DATE.format(value));
73+ }
74+
75+ @Override
76+ public LocalDate parse(String value) {
77+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
78+ return null;
79+
80+ // single quotes are optional for long literals, mandatory for date patterns
81+ // strip enclosing single quotes, if any
82+ if (isQuoted(value))
83+ value = unquote(value);
84+
85+ if (isLongLiteral(value)) {
86+ long raw;
87+ try {
88+ raw = parseLong(value);
89+ } catch (NumberFormatException e) {
90+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
91+ }
92+ int days;
93+ try {
94+ days = fromCqlDateToDaysSinceEpoch(raw);
95+ } catch (IllegalArgumentException e) {
96+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
97+ }
98+ return EPOCH.plusDays(days);
99+ }
100+
101+ try {
102+ return LocalDate.parse(value, ISO_LOCAL_DATE);
103+ } catch (RuntimeException e) {
104+ throw new InvalidTypeException(String.format("Cannot parse date value from \"%s\"", value));
105+ }
106+ }
107+
108+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodec.java +94 −0
@@ -0,0 +1,94 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.LocalTime;
20+import java.time.format.DateTimeFormatter;
21+
22+import com.datastax.driver.core.DataType;
23+import com.datastax.driver.core.ParseUtils;
24+import com.datastax.driver.core.ProtocolVersion;
25+import com.datastax.driver.core.TypeCodec;
26+import com.datastax.driver.core.exceptions.InvalidTypeException;
27+
28+import static com.datastax.driver.core.ParseUtils.quote;
29+
30+/**
31+ * {@link TypeCodec} that maps {@link LocalTime} <-> CQL time (long representing nanoseconds since midnight)
32+ * allowing the setting and retrieval of <code>time</code> columns as {@link LocalTime}
33+ * instances.
34+ */
35+public class LocalTimeCodec extends TypeCodec<LocalTime> {
36+
37+ public static final LocalTimeCodec instance = new LocalTimeCodec();
38+
39+ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
40+
41+ private LocalTimeCodec() {
42+ super(DataType.time(), LocalTime.class);
43+ }
44+
45+ @Override
46+ public ByteBuffer serialize(LocalTime value, ProtocolVersion protocolVersion) throws InvalidTypeException {
47+ if (value == null)
48+ return null;
49+ return bigint().serializeNoBoxing(value.toNanoOfDay(), protocolVersion);
50+ }
51+
52+ @Override
53+ public LocalTime deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54+ if (bytes == null || bytes.remaining() == 0)
55+ return null;
56+ long nanosOfDay = bigint().deserializeNoBoxing(bytes, protocolVersion);
57+ return LocalTime.ofNanoOfDay(nanosOfDay);
58+ }
59+
60+ @Override
61+ public String format(LocalTime value) {
62+ if (value == null)
63+ return "NULL";
64+ return quote(FORMATTER.format(value));
65+ }
66+
67+ @Override
68+ public LocalTime parse(String value) {
69+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
70+ return null;
71+
72+ // enclosing single quotes required, even for long literals
73+ if (!ParseUtils.isQuoted(value))
74+ throw new InvalidTypeException("time values must be enclosed by single quotes");
75+ value = value.substring(1, value.length() - 1);
76+
77+ if (ParseUtils.isLongLiteral(value)) {
78+ long nanosOfDay;
79+ try {
80+ nanosOfDay = Long.parseLong(value);
81+ } catch (NumberFormatException e) {
82+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
83+ }
84+ return LocalTime.ofNanoOfDay(nanosOfDay);
85+ }
86+
87+ try {
88+ return LocalTime.parse(value);
89+ } catch (RuntimeException e) {
90+ throw new InvalidTypeException(String.format("Cannot parse time value from \"%s\"", value), e);
91+ }
92+ }
93+
94+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodec.java +73 −0
@@ -0,0 +1,73 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.util.Collection;
19+import java.util.Map;
20+import java.util.Optional;
21+import java.util.function.Predicate;
22+
23+import com.google.common.reflect.TypeParameter;
24+import com.google.common.reflect.TypeToken;
25+
26+import com.datastax.driver.core.TypeCodec;
27+import com.datastax.driver.extras.codecs.MappingCodec;
28+
29+/**
30+ * A codec that wraps other codecs around JDK 8's {@link Optional} API.
31+ *
32+ * @param <T> The wrapped Java type
33+ */
34+public class OptionalCodec<T> extends MappingCodec<Optional<T>, T> {
35+
36+ private final Predicate<T> isAbsent;
37+
38+ public OptionalCodec(TypeCodec<T> codec) {
39+ this(codec, new Predicate<T>() {
40+ @Override
41+ public boolean test(T input) {
42+ return input == null
43+ || input instanceof Collection && ((Collection)input).isEmpty()
44+ || input instanceof Map && ((Map)input).isEmpty();
45+
46+ }
47+ });
48+ }
49+
50+ public OptionalCodec(TypeCodec<T> codec, Predicate<T> isAbsent) {
51+ super(codec, new TypeToken<Optional<T>>(){}.where(new TypeParameter<T>(){}, codec.getJavaType()));
52+ this.isAbsent = isAbsent;
53+ }
54+
55+ @Override
56+ protected Optional<T> deserialize(T value) {
57+ return isAbsent(value) ? Optional.<T>empty() : Optional.of(value);
58+ }
59+
60+ @Override
61+ protected T serialize(Optional<T> value) {
62+ return value.isPresent() ? value.get() : absentValue();
63+ }
64+
65+ protected T absentValue() {
66+ return null;
67+ }
68+
69+ protected boolean isAbsent(T value) {
70+ return isAbsent.test(value);
71+ }
72+
73+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodec.java +164 −0
@@ -0,0 +1,164 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.nio.ByteBuffer;
19+import java.time.Instant;
20+import java.time.ZoneId;
21+import java.time.ZoneOffset;
22+import java.time.ZonedDateTime;
23+import java.time.format.DateTimeFormatter;
24+import java.time.format.DateTimeFormatterBuilder;
25+import java.time.format.DateTimeParseException;
26+import java.util.List;
27+
28+import static java.time.temporal.ChronoField.HOUR_OF_DAY;
29+import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
30+import static java.time.temporal.ChronoField.NANO_OF_SECOND;
31+import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
32+
33+import static com.google.common.base.Preconditions.checkArgument;
34+
35+import com.datastax.driver.core.*;
36+import com.datastax.driver.core.exceptions.InvalidTypeException;
37+
38+import static com.datastax.driver.core.ParseUtils.isLongLiteral;
39+import static com.datastax.driver.core.ParseUtils.quote;
40+
41+/**
42+ * <p>
43+ * {@link TypeCodec} that maps
44+ * {@link ZonedDateTime} <-> <code>tuple&lt;timestamp,varchar&gt;</code>
45+ * providing a pattern for maintaining timezone information in
46+ * Cassandra.
47+ *
48+ * <p>
49+ * Since Cassandra's <code>timestamp</code> type preserves only
50+ * milliseconds since epoch, any timezone information
51+ * would normally be lost. By using a
52+ * <code>tuple&lt;timestamp,varchar&gt;</code> a timezone ID can be
53+ * persisted in the <code>varchar</code> field such that when the
54+ * value is deserialized the timezone is
55+ * preserved.
56+ */
57+public class ZonedDateTimeCodec extends TypeCodec.AbstractTupleCodec<ZonedDateTime> {
58+
59+ /**
60+ * A {@link DateTimeFormatter} that parses (most) of
61+ * the ISO formats accepted in CQL.
62+ */
63+ private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
64+ .parseCaseSensitive()
65+ .parseStrict()
66+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
67+ .optionalStart()
68+ .appendLiteral('T')
69+ .appendValue(HOUR_OF_DAY, 2)
70+ .appendLiteral(':')
71+ .appendValue(MINUTE_OF_HOUR, 2)
72+ .optionalEnd()
73+ .optionalStart()
74+ .appendLiteral(':')
75+ .appendValue(SECOND_OF_MINUTE, 2)
76+ .optionalEnd()
77+ .optionalStart()
78+ .appendFraction(NANO_OF_SECOND, 0, 9, true)
79+ .optionalEnd()
80+ .optionalStart()
81+ .appendZoneOrOffsetId()
82+ .optionalEnd()
83+ .toFormatter()
84+ .withZone(ZoneOffset.UTC);
85+
86+ private static final DateTimeFormatter ZONE_FORMATTER = DateTimeFormatter.ofPattern("xxx");
87+
88+ public ZonedDateTimeCodec(TupleType tupleType) {
89+ super(tupleType, ZonedDateTime.class);
90+ List<DataType> types = tupleType.getComponentTypes();
91+ checkArgument(
92+ types.size() == 2 && types.get(0).equals(DataType.timestamp()) && types.get(1).equals(DataType.varchar()),
93+ "Expected tuple<timestamp,varchar>, got %s",
94+ tupleType);
95+ }
96+
97+ @Override
98+ protected ZonedDateTime newInstance() {
99+ return null;
100+ }
101+
102+ @Override
103+ protected ByteBuffer serializeField(ZonedDateTime source, int index, ProtocolVersion protocolVersion) {
104+ if(index == 0) {
105+ long millis = source.toInstant().toEpochMilli();
106+ return bigint().serializeNoBoxing(millis, protocolVersion);
107+ }
108+ if(index == 1) {
109+ return varchar().serialize(ZONE_FORMATTER.format(source.getOffset()), protocolVersion);
110+ }
111+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
112+ }
113+
114+ @Override
115+ protected ZonedDateTime deserializeAndSetField(ByteBuffer input, ZonedDateTime target, int index, ProtocolVersion protocolVersion) {
116+ if(index == 0) {
117+ long millis = bigint().deserializeNoBoxing(input, protocolVersion);
118+ return Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC);
119+ }
120+ if(index == 1) {
121+ String zoneId = varchar().deserialize(input, protocolVersion);
122+ return target.withZoneSameInstant(ZoneId.of(zoneId));
123+ }
124+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
125+ }
126+
127+ @Override
128+ protected String formatField(ZonedDateTime value, int index) {
129+ if(index == 0) {
130+ return quote(FORMATTER.format(value));
131+ }
132+ if(index == 1) {
133+ return quote(ZONE_FORMATTER.format(value.getOffset()));
134+ }
135+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
136+ }
137+
138+ @Override
139+ protected ZonedDateTime parseAndSetField(String input, ZonedDateTime target, int index) {
140+ if(index == 0) {
141+ // strip enclosing single quotes, if any
142+ if (ParseUtils.isQuoted(input))
143+ input = ParseUtils.unquote(input);
144+ if (isLongLiteral(input)) {
145+ try {
146+ long millis = Long.parseLong(input);
147+ return ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC);
148+ } catch (NumberFormatException e) {
149+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", input));
150+ }
151+ }
152+ try {
153+ return ZonedDateTime.from(FORMATTER.parse(input));
154+ } catch (DateTimeParseException e) {
155+ throw new InvalidTypeException(String.format("Cannot parse timestamp value from \"%s\"", target));
156+ }
157+ }
158+ if(index == 1) {
159+ String zoneId = varchar().parse(input);
160+ return target.withZoneSameInstant(ZoneId.of(zoneId));
161+ }
162+ throw new IndexOutOfBoundsException("Tuple index out of bounds. "+ index);
163+ }
164+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/jdk8/package-info.java +61 −0
@@ -0,0 +1,61 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec TypeCodec} instances useful for
20+ * serializing between CQL types and JDK 8 types, such as the ones from the
21+ * {@code java.time} API and {@link java.util.Optional}.
22+ * <p>
23+ * The codecs in this class provide the following mappings:
24+ *
25+ * <table summary="Supported Mappings">
26+ * <tr>
27+ * <th>Codec</th>
28+ * <th>CQL type</th>
29+ * <th>JDK 8 type</th>
30+ * </tr>
31+ * <tr>
32+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.OptionalCodec}</td>
33+ * <td>Any</td>
34+ * <td>{@link java.util.Optional Optional}</td>
35+ * </tr>
36+ * <tr>
37+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.LocalTimeCodec}</td>
38+ * <td>{@link com.datastax.driver.core.DataType#time() time}</td>
39+ * <td>{@link java.time.LocalTime LocalTime}</td>
40+ * </tr>
41+ * <tr>
42+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.LocalDateCodec}</td>
43+ * <td>{@link com.datastax.driver.core.DataType#date() date}</td>
44+ * <td>{@link java.time.LocalDate LocalDate}</td>
45+ * </tr>
46+ * <tr>
47+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.InstantCodec}</td>
48+ * <td>{@link com.datastax.driver.core.DataType#timestamp() timestamp}</td>
49+ * <td>{@link java.time.Instant Instant}</td>
50+ * </tr>
51+ * <tr>
52+ * <td>{@link com.datastax.driver.extras.codecs.jdk8.ZonedDateTimeCodec}</td>
53+ * <td>{@link com.datastax.driver.core.TupleType tuple} of
54+ * ({@link com.datastax.driver.core.DataType#timestamp() timestamp},
55+ * {@link com.datastax.driver.core.DataType#varchar() varchar})</td>
56+ * <td>{@link java.time.ZonedDateTime ZonedDateTime}</td>
57+ * </tr>
58+ * </table>
59+ *
60+ */
61+package com.datastax.driver.extras.codecs.jdk8;
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/InstantCodecTest.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.Instant;
19+import java.time.ZonedDateTime;
20+
21+import org.testng.annotations.DataProvider;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.Assertions;
27+
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class InstantCodecTest {
31+
32+ @DataProvider(name = "InstantCodecTest.parse")
33+ public Object[][] parseParameters() {
34+ return new Object[][]{
35+ { null , null },
36+ { "" , null },
37+ { "NULL" , null },
38+ { "0" , Instant.ofEpochMilli(0) },
39+ { "1277860847999" , Instant.ofEpochMilli(1277860847999L) },
40+ { "'2010-06-30T01:20'" , Instant.parse("2010-06-30T01:20:00.000Z") },
41+ { "'2010-06-30T01:20Z'" , Instant.parse("2010-06-30T01:20:00.000Z") },
42+ { "'2010-06-30T01:20:47'" , Instant.parse("2010-06-30T01:20:47.000Z") },
43+ { "'2010-06-30T01:20:47+01:00'" , Instant.parse("2010-06-30T00:20:47.000Z") },
44+ { "'2010-06-30T01:20:47.999'" , Instant.parse("2010-06-30T01:20:47.999Z") },
45+ { "'2010-06-30T01:20:47.999+01:00'" , Instant.parse("2010-06-30T00:20:47.999Z") }
46+ };
47+ }
48+
49+ @DataProvider(name = "InstantCodecTest.format")
50+ public Object[][] formatParameters() {
51+ return new Object[][]{
52+ { null , "NULL" },
53+ { Instant.ofEpochMilli(0) , "'1970-01-01T00:00:00.000+00:00'" },
54+ { ZonedDateTime.parse("2010-06-30T02:20:47.999+01:00").toInstant(), "'2010-06-30T01:20:47.999+00:00'" }
55+ };
56+ }
57+
58+ @Test(groups = "unit", dataProvider = "InstantCodecTest.parse")
59+ public void should_parse_valid_formats(String input, Instant expected) {
60+ // when
61+ Instant actual = InstantCodec.instance.parse(input);
62+ // then
63+ assertThat(actual).isEqualTo(expected);
64+ }
65+
66+ @Test(groups = "unit", dataProvider = "InstantCodecTest.format")
67+ public void should_serialize_and_format_valid_object(Instant input, String expected) {
68+ // when
69+ String actual = InstantCodec.instance.format(input);
70+ // then
71+ Assertions.assertThat(InstantCodec.instance).withProtocolVersion(V4).canSerialize(input);
72+ assertThat(actual).isEqualTo(expected);
73+ }
74+
75+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/Jdk8TimeCodecsTest.java +307 −0
@@ -0,0 +1,307 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.Instant;
19+import java.time.LocalDate;
20+import java.time.LocalTime;
21+import java.time.ZonedDateTime;
22+import java.util.*;
23+
24+import com.google.common.collect.ImmutableMap;
25+import org.testng.annotations.BeforeClass;
26+import org.testng.annotations.Test;
27+
28+import static com.google.common.collect.Lists.newArrayList;
29+import static com.google.common.collect.Sets.newHashSet;
30+import static org.assertj.core.api.Assertions.assertThat;
31+
32+import com.datastax.driver.core.*;
33+import com.datastax.driver.core.utils.CassandraVersion;
34+import com.datastax.driver.mapping.Mapper;
35+import com.datastax.driver.mapping.MappingManager;
36+import com.datastax.driver.mapping.annotations.Column;
37+import com.datastax.driver.mapping.annotations.PartitionKey;
38+import com.datastax.driver.mapping.annotations.Table;
39+
40+import static com.datastax.driver.core.DataType.timestamp;
41+import static com.datastax.driver.core.DataType.varchar;
42+
43+@CassandraVersion(major=2.2)
44+public class Jdk8TimeCodecsTest extends CCMBridge.PerClassSingleNodeCluster {
45+
46+ @Override
47+ protected Collection<String> getTableDefinitions() {
48+ return Collections.singletonList(
49+ "CREATE TABLE IF NOT EXISTS foo ("
50+ + "c1 text PRIMARY KEY, "
51+ + "cdate date, "
52+ + "ctime time, "
53+ + "ctimestamp timestamp, "
54+ + "ctuple tuple<timestamp,varchar>, "
55+ + "cdates frozen<list<date>>, "
56+ + "ctimes frozen<set<time>>, "
57+ + "ctimestamps frozen<map<text,timestamp>>, "
58+ + "ctuples frozen<map<tuple<timestamp,varchar>,varchar>>"
59+ + ")");
60+ }
61+
62+ @BeforeClass(groups = "short")
63+ public void registerCodecs() throws Exception {
64+ TupleType dateWithTimeZoneType = cluster.getMetadata().newTupleType(timestamp(), varchar());
65+ CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();
66+ codecRegistry
67+ .register(LocalTimeCodec.instance)
68+ .register(LocalDateCodec.instance)
69+ .register(InstantCodec.instance)
70+ .register(new ZonedDateTimeCodec(dateWithTimeZoneType));
71+ }
72+
73+ /**
74+ * <p>
75+ * Validates that a <code>time</code> column can be mapped to a {@link LocalTime} by using
76+ * {@link LocalTimeCodec}.
77+ * </p>
78+ *
79+ * @test_category data_types:serialization
80+ * @expected_result properly maps.
81+ * @jira_ticket JAVA-606
82+ * @since 2.2.0
83+ */
84+ @Test(groups="short")
85+ public void should_map_time_to_localtime() {
86+ // given
87+ LocalTime time = LocalTime.of(12, 16, 34, 999);
88+ // when
89+ session.execute("insert into foo (c1, ctime) values (?, ?)", "should_map_time_to_localtime", time);
90+ ResultSet result = session.execute("select ctime from foo where c1=?", "should_map_time_to_localtime");
91+ // then
92+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
93+ Row row = result.one();
94+ assertThat(row.get("ctime", LocalTime.class)).isEqualTo(time);
95+ assertThat(row.getTime("ctime")).isEqualTo(time.toNanoOfDay());
96+ }
97+
98+ /**
99+ * <p>
100+ * Validates that a <code>date</code> column can be mapped to a {@link LocalDate} by using
101+ * {@link LocalDateCodec}.
102+ * </p>
103+ *
104+ * @test_category data_types:serialization
105+ * @expected_result properly maps.
106+ * @jira_ticket JAVA-606
107+ * @since 2.2.0
108+ */
109+ @Test(groups="short")
110+ public void should_map_date_to_localdate() {
111+ // given
112+ LocalDate localDate = LocalDate.of(2015, 1, 1);
113+ com.datastax.driver.core.LocalDate driverLocalDate = com.datastax.driver.core.LocalDate.fromYearMonthDay(2015, 1, 1);
114+ // when
115+ session.execute("insert into foo (c1, cdate) values (?, ?)", "should_map_date_to_localdate", localDate);
116+ ResultSet result = session.execute("select cdate from foo where c1=?", "should_map_date_to_localdate");
117+ // then
118+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
119+ Row row = result.one();
120+ assertThat(row.get("cdate", LocalDate.class)).isEqualTo(localDate);
121+ assertThat(row.getDate("cdate")).isEqualTo(driverLocalDate);
122+ }
123+
124+ /**
125+ * <p>
126+ * Validates that a <code>timestamp</code> column can be mapped to a {@link Instant} by using
127+ * {@link InstantCodec}.
128+ * </p>
129+ *
130+ * @test_category data_types:serialization
131+ * @expected_result properly maps.
132+ * @jira_ticket JAVA-606
133+ * @since 2.2.0
134+ */
135+ @Test(groups="short")
136+ public void should_map_timestamp_to_instant() {
137+ // given
138+ Instant instant = Instant.parse("2010-06-30T01:20:30Z");
139+ // when
140+ session.execute("insert into foo (c1, ctimestamp) values (?, ?)", "should_map_timestamp_to_instant", instant);
141+ ResultSet result = session.execute("select ctimestamp from foo where c1=?", "should_map_timestamp_to_instant");
142+ // then
143+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
144+ Row row = result.one();
145+ assertThat(row.get("ctimestamp", Instant.class)).isEqualTo(instant);
146+ assertThat(row.getTimestamp("ctimestamp")).isEqualTo(Date.from(instant));
147+ }
148+
149+ /**
150+ * <p>
151+ * Validates that a <code>tuple&lt;timestamp,text&gt;</code> column can be mapped to a {@link ZonedDateTime} by using
152+ * {@link ZonedDateTimeCodec}.
153+ * </p>
154+ *
155+ * @test_category data_types:serialization
156+ * @expected_result properly maps.
157+ * @jira_ticket JAVA-606
158+ * @since 2.2.0
159+ */
160+ @Test(groups="short")
161+ public void should_map_tuple_to_zoneddatetime() {
162+ // given
163+ ZonedDateTime expected = ZonedDateTime.parse("2010-06-30T01:20+05:30");
164+ // when
165+ PreparedStatement insertStmt = session.prepare("insert into foo (c1, ctuple) values (?, ?)");
166+ session.execute(insertStmt.bind("should_map_tuple_to_instant", expected));
167+ ResultSet result = session.execute("select ctuple from foo where c1=?", "should_map_tuple_to_instant");
168+ // then
169+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
170+ Row row = result.one();
171+ ZonedDateTime actual = row.get("ctuple", ZonedDateTime.class);
172+ // Since timezone is preserved in the tuple, the date times should match perfectly.
173+ assertThat(actual).isEqualTo(expected);
174+ // Ensure the timezones match as well.
175+ // (This is just a safety check as the previous assert would have failed otherwise).
176+ assertThat(actual.getZone()).isEqualTo(expected.getZone());
177+ }
178+
179+ @Test(groups="short")
180+ public void should_use_mapper_to_store_and_retrieve_values_with_custom_jdk8_codecs() {
181+ // given
182+ MappingManager manager = new MappingManager(session);
183+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
184+ // when
185+ Mapped pojo = new Mapped();
186+ mapper.save(pojo);
187+ Mapped actual = mapper.get("mapper");
188+ // then
189+ assertThat(actual).isEqualToComparingFieldByField(pojo);
190+ }
191+
192+ @SuppressWarnings("unused")
193+ @Table(name = "foo")
194+ public static class Mapped {
195+
196+ @PartitionKey
197+ private String c1;
198+
199+ @Column(name = "cdate")
200+ private LocalDate date;
201+
202+ @Column(name = "ctime")
203+ private LocalTime time;
204+
205+ @Column(name = "ctimestamp")
206+ private Instant instant;
207+
208+ @Column(name = "ctuple")
209+ private ZonedDateTime zdt;
210+
211+ @Column(name = "cdates")
212+ private List<LocalDate> dates;
213+
214+ @Column(name = "ctimes")
215+ private Set<LocalTime> times;
216+
217+ @Column(name = "ctimestamps")
218+ private Map<String, Instant> instants;
219+
220+ @Column(name = "ctuples")
221+ private Map<ZonedDateTime, String> zdts;
222+
223+ public Mapped() {
224+ c1 = "mapper";
225+ date = LocalDate.parse("2014-01-01");
226+ time = LocalTime.NOON;
227+ instant = Instant.parse("2010-06-30T01:20:47.000Z");
228+ zdt = ZonedDateTime.parse("2010-06-30T01:20:47+05:30");
229+ dates = newArrayList(date);
230+ times = newHashSet(time);
231+ instants = ImmutableMap.of("foo", instant);
232+ zdts = ImmutableMap.of(zdt, "bar");
233+ }
234+
235+ public String getC1() {
236+ return c1;
237+ }
238+
239+ public void setC1(String c1) {
240+ this.c1 = c1;
241+ }
242+
243+ public LocalDate getDate() {
244+ return date;
245+ }
246+
247+ public void setDate(LocalDate date) {
248+ this.date = date;
249+ }
250+
251+ public LocalTime getTime() {
252+ return time;
253+ }
254+
255+ public void setTime(LocalTime time) {
256+ this.time = time;
257+ }
258+
259+ public Instant getInstant() {
260+ return instant;
261+ }
262+
263+ public void setInstant(Instant instant) {
264+ this.instant = instant;
265+ }
266+
267+ public ZonedDateTime getZdt() {
268+ return zdt;
269+ }
270+
271+ public void setZdt(ZonedDateTime zdt) {
272+ this.zdt = zdt;
273+ }
274+
275+ public List<LocalDate> getDates() {
276+ return dates;
277+ }
278+
279+ public void setDates(List<LocalDate> dates) {
280+ this.dates = dates;
281+ }
282+
283+ public Set<LocalTime> getTimes() {
284+ return times;
285+ }
286+
287+ public void setTimes(Set<LocalTime> times) {
288+ this.times = times;
289+ }
290+
291+ public Map<String, Instant> getInstants() {
292+ return instants;
293+ }
294+
295+ public void setInstants(Map<String, Instant> instants) {
296+ this.instants = instants;
297+ }
298+
299+ public Map<ZonedDateTime, String> getZdts() {
300+ return zdts;
301+ }
302+
303+ public void setZdts(Map<ZonedDateTime, String> zdts) {
304+ this.zdts = zdts;
305+ }
306+ }
307+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalDateCodecTest.java +74 −0
@@ -0,0 +1,74 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.LocalDate;
19+
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+import com.datastax.driver.core.Assertions;
26+
27+import static com.datastax.driver.core.ProtocolVersion.V4;
28+
29+public class LocalDateCodecTest {
30+
31+ private static final LocalDate EPOCH = LocalDate.ofEpochDay(0);
32+ private static final LocalDate MIN = LocalDate.parse("-5877641-06-23");
33+
34+ @DataProvider(name = "LocalDateCodecTest.parse")
35+ public Object[][] parseParameters() {
36+ return new Object[][]{
37+ { null , null },
38+ { "" , null },
39+ { "NULL" , null },
40+ { "0" , MIN },
41+ { "'2147483648'" , EPOCH },
42+ { "'-5877641-06-23'" , MIN },
43+ { "'1970-01-01'" , EPOCH },
44+ { "'2014-01-01'" , LocalDate.parse("2014-01-01") }
45+ };
46+ }
47+
48+ @DataProvider(name = "LocalDateCodecTest.format")
49+ public Object[][] formatParameters() {
50+ return new Object[][]{
51+ { null , "NULL" },
52+ { LocalDate.ofEpochDay(0) , "'1970-01-01'" },
53+ { LocalDate.parse("2010-06-30"), "'2010-06-30'" }
54+ };
55+ }
56+
57+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest.parse")
58+ public void should_parse_valid_formats(String input, LocalDate expected) {
59+ // when
60+ LocalDate actual = LocalDateCodec.instance.parse(input);
61+ // then
62+ assertThat(actual).isEqualTo(expected);
63+ }
64+
65+ @Test(groups = "unit", dataProvider = "LocalDateCodecTest.format")
66+ public void should_serialize_and_format_valid_object(LocalDate input, String expected) {
67+ // when
68+ String actual = LocalDateCodec.instance.format(input);
69+ // then
70+ Assertions.assertThat(LocalDateCodec.instance).withProtocolVersion(V4).canSerialize(input);
71+ assertThat(actual).isEqualTo(expected);
72+ }
73+
74+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/LocalTimeCodecTest.java +74 −0
@@ -0,0 +1,74 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.LocalTime;
19+
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+import com.datastax.driver.core.Assertions;
26+
27+import static com.datastax.driver.core.ParseUtils.quote;
28+import static com.datastax.driver.core.ProtocolVersion.V4;
29+
30+public class LocalTimeCodecTest {
31+
32+ @DataProvider(name = "LocalTimeCodecTest.parse")
33+ public Object[][] parseParameters() {
34+ LocalTime time = LocalTime.parse("13:25:47.123456789");
35+ String nanosOfDay = quote(Long.toString(time.toNanoOfDay()));
36+ return new Object[][]{
37+ { null , null },
38+ { "" , null },
39+ { "NULL" , null },
40+ { nanosOfDay , LocalTime.parse("13:25:47.123456789") },
41+ { "'13:25:47'" , LocalTime.parse("13:25:47") },
42+ { "'13:25:47.123'" , LocalTime.parse("13:25:47.123") },
43+ { "'13:25:47.123456'" , LocalTime.parse("13:25:47.123456") },
44+ { "'13:25:47.123456789'", LocalTime.parse("13:25:47.123456789") }
45+ };
46+ }
47+
48+ @DataProvider(name = "LocalTimeCodecTest.format")
49+ public Object[][] formatParameters() {
50+ return new Object[][]{
51+ { null , "NULL" },
52+ { LocalTime.NOON , "'12:00:00.000'" },
53+ { LocalTime.parse("02:20:47.999999"), "'02:20:47.999'" }
54+ };
55+ }
56+
57+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.parse")
58+ public void should_parse_valid_formats(String input, LocalTime expected) {
59+ // when
60+ LocalTime actual = LocalTimeCodec.instance.parse(input);
61+ // then
62+ assertThat(actual).isEqualTo(expected);
63+ }
64+
65+ @Test(groups = "unit", dataProvider = "LocalTimeCodecTest.format")
66+ public void should_serialize_and_format_valid_object(LocalTime input, String expected) {
67+ // when
68+ String actual = LocalTimeCodec.instance.format(input);
69+ // then
70+ Assertions.assertThat(LocalTimeCodec.instance).withProtocolVersion(V4).canSerialize(input);
71+ assertThat(actual).isEqualTo(expected);
72+ }
73+
74+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/OptionalCodecTest.java +218 −0
@@ -0,0 +1,218 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.math.BigDecimal;
19+import java.util.Collection;
20+import java.util.Collections;
21+import java.util.List;
22+import java.util.Optional;
23+
24+import com.google.common.collect.Lists;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static org.assertj.core.api.Assertions.assertThat;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.CCMBridge.PerClassSingleNodeCluster;
32+import com.datastax.driver.core.querybuilder.BuiltStatement;
33+import com.datastax.driver.core.querybuilder.QueryBuilder;
34+import com.datastax.driver.core.utils.CassandraVersion;
35+
36+import static com.datastax.driver.core.TypeCodec.bigint;
37+import static com.datastax.driver.core.TypeCodec.decimal;
38+import static com.datastax.driver.core.TypeCodec.list;
39+import static com.datastax.driver.core.TypeCodec.varchar;
40+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
41+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
42+
43+public class OptionalCodecTest extends PerClassSingleNodeCluster {
44+
45+ private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar()));
46+
47+ private final CodecRegistry registry = new CodecRegistry().register(optionalCodec);
48+
49+ private BuiltStatement insertStmt;
50+
51+ private BuiltStatement selectStmt;
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Collections.singletonList("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))");
56+ }
57+
58+ @Override
59+ protected Cluster.Builder configure(Cluster.Builder builder) {
60+ return builder.withCodecRegistry(registry);
61+ }
62+
63+ @BeforeMethod(groups = "short")
64+ public void createBuiltStatements() throws Exception {
65+ insertStmt = new QueryBuilder(cluster).insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker());
66+ selectStmt = new QueryBuilder(cluster).select("c2", "c3").from("foo").where(eq("c1", bindMarker()));
67+ }
68+
69+ /**
70+ * <p>
71+ * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return
72+ * an {@link Optional#empty()} value. Since CQL Lists can't differentiate between null and empty lists, the
73+ * OptionalCodec should be smart enough to map an empty list to empty.
74+ * </p>
75+ *
76+ * @test_category data_types:serialization
77+ * @expected_result an empty value.
78+ * @jira_ticket JAVA-606
79+ * @since 2.2.0
80+ */
81+ @Test(groups="short")
82+ @CassandraVersion(major=2.2)
83+ public void should_map_unset_value_to_empty() {
84+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
85+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
86+
87+ BoundStatement bs = insertPrep.bind();
88+ bs.setString(0, "should_map_unset_value_to_empty");
89+ bs.setString(1, "1");
90+ session.execute(bs);
91+
92+ ResultSet results = session.execute(selectPrep.bind("should_map_unset_value_to_empty"));
93+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
94+
95+ Row row = results.one();
96+ assertThat(row.getString("c2")).isEqualTo("1");
97+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.empty());
98+ }
99+
100+ /**
101+ * <p>
102+ * Validates that if a column is set to {@link Optional#empty()} using {@link OptionalCodec} that it should be
103+ * stored as null and that retrieving it should return {@link Optional#empty()} using {@link OptionalCodec}.
104+ * </p>
105+ *
106+ * @test_category data_types:serialization
107+ * @expected_result an empty value.
108+ * @jira_ticket JAVA-606
109+ * @since 2.2.0
110+ */
111+ @Test(groups="short")
112+ public void should_map_absent_null_value_to_empty() {
113+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
114+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
115+
116+ BoundStatement bs = insertPrep.bind();
117+ bs.setString(0, "should_map_absent_null_value_to_empty");
118+ bs.setString(1, "1");
119+ bs.set(2, Optional.<List<String>>empty(), optionalCodec.getJavaType());
120+ session.execute(bs);
121+
122+ ResultSet results = session.execute(selectPrep.bind("should_map_absent_null_value_to_empty"));
123+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
124+
125+ Row row = results.one();
126+ assertThat(row.getString("c2")).isEqualTo("1");
127+ assertThat(row.getList("c3", String.class)).isEmpty();
128+ assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.empty());
129+ }
130+
131+ /**
132+ * <p>
133+ * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be
134+ * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec}
135+ * and its actual value without using it.
136+ * </p>
137+ *
138+ * @test_category data_types:serialization
139+ * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec.
140+ * @jira_ticket JAVA-606
141+ * @since 2.2.0
142+ */
143+ @Test(groups="short")
144+ public void should_map_some_back_to_itself() {
145+ PreparedStatement insertPrep = session.prepare(this.insertStmt);
146+ PreparedStatement selectPrep = session.prepare(this.selectStmt);
147+
148+ List<String> data = Lists.newArrayList("1", "2", "3");
149+
150+ BoundStatement bs = insertPrep.bind();
151+ bs.setString(0, "should_map_some_back_to_itself");
152+ bs.setString(1, "1");
153+ bs.set(2, Optional.of(data), optionalCodec.getJavaType());
154+ session.execute(bs);
155+
156+ ResultSet results = session.execute(selectPrep.bind("should_map_some_back_to_itself"));
157+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
158+
159+ Row row = results.one();
160+ assertThat(row.getString("c2")).isEqualTo("1");
161+
162+ // Ensure data stored correctly.
163+ assertThat(row.getList("c3", String.class)).isEqualTo(data);
164+
165+ // Ensure data retrievable using Option codec.
166+ Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType());
167+ assertThat(returnData.isPresent()).isTrue();
168+ assertThat(returnData.get()).isEqualTo(data);
169+ }
170+
171+ @Test(groups="short")
172+ public void should_map_a_primitive_type_to_empty() {
173+ OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint());
174+ cluster.getConfiguration().getCodecRegistry().register(optionalLongCodec);
175+
176+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c4) values (?,?,?)");
177+
178+ BoundStatement bs = stmt.bind();
179+ bs.setString(0, "should_map_a_primitive_type_to_empty");
180+ bs.setString(1, "1");
181+ bs.set(2, Optional.<Long>empty(), optionalLongCodec.getJavaType());
182+ session.execute(bs);
183+
184+ PreparedStatement selectBigint = session.prepare("select c1, c4 from foo where c1=?");
185+ ResultSet results = session.execute(selectBigint.bind("should_map_a_primitive_type_to_empty"));
186+
187+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
188+
189+ Row row = results.one();
190+ assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>empty());
191+ assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value.
192+ assertThat(row.get("c4", Long.class)).isNull();
193+ }
194+
195+ @Test(groups="short")
196+ public void should_map_a_nullable_type_to_empty() {
197+ OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal());
198+ cluster.getConfiguration().getCodecRegistry().register(optionalDecimalCodec);
199+
200+ PreparedStatement stmt = session.prepare("insert into foo (c1, c2, c5) values (?,?,?)");
201+
202+ BoundStatement bs = stmt.bind();
203+ bs.setString(0, "should_map_a_nullable_type_to_empty");
204+ bs.setString(1, "1");
205+ bs.set(2, Optional.<BigDecimal>empty(), optionalDecimalCodec.getJavaType());
206+ session.execute(bs);
207+
208+ PreparedStatement selectDecimal = session.prepare("select c1, c5 from foo where c1=?");
209+ ResultSet results = session.execute(selectDecimal.bind("should_map_a_nullable_type_to_empty"));
210+
211+ assertThat(results.getAvailableWithoutFetching()).isEqualTo(1);
212+
213+ Row row = results.one();
214+ assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>empty());
215+ assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null.
216+ }
217+
218+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/jdk8/ZonedDateTimeCodecTest.java +92 −0
@@ -0,0 +1,92 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.jdk8;
17+
18+import java.time.ZoneOffset;
19+import java.time.ZonedDateTime;
20+
21+import static java.time.Instant.ofEpochMilli;
22+import static java.time.Instant.parse;
23+import static java.time.ZoneOffset.UTC;
24+import static java.time.ZonedDateTime.ofInstant;
25+
26+import org.testng.annotations.DataProvider;
27+import org.testng.annotations.Test;
28+
29+import static com.google.common.collect.Lists.newArrayList;
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Mockito.mock;
32+import static org.mockito.Mockito.when;
33+
34+import com.datastax.driver.core.Assertions;
35+import com.datastax.driver.core.TupleType;
36+
37+import static com.datastax.driver.core.DataType.timestamp;
38+import static com.datastax.driver.core.DataType.varchar;
39+import static com.datastax.driver.core.ProtocolVersion.V4;
40+
41+public class ZonedDateTimeCodecTest {
42+
43+ private final TupleType tupleType = mock(TupleType.class);
44+
45+ @DataProvider(name = "ZonedDateTimeCodecTest.parse")
46+ public Object[][] parseParameters() {
47+ return new Object[][]{
48+ { null , null },
49+ { "" , null },
50+ { "NULL" , null },
51+ { "(0 ,'+01:00')" , ofInstant(ofEpochMilli(0) , ZoneOffset.of("+01:00")) },
52+ { "(1277860847999 ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) },
53+ { "('2010-06-30T01:20Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:00.000Z"), ZoneOffset.of("+01:00")) },
54+ { "('2010-06-30T01:20:47Z' ,'+01:00')" , ofInstant(parse("2010-06-30T01:20:47.000Z"), ZoneOffset.of("+01:00")) },
55+ { "('2010-06-30T01:20:47.999Z','+01:00')" , ofInstant(parse("2010-06-30T01:20:47.999Z"), ZoneOffset.of("+01:00")) }
56+ };
57+ }
58+
59+ @DataProvider(name = "ZonedDateTimeCodecTest.format")
60+ public Object[][] formatParameters() {
61+ return new Object[][]{
62+ { null , "NULL" },
63+ { ofInstant(ofEpochMilli(0), UTC) , "('1970-01-01T00:00:00Z','+00:00')" },
64+ { ZonedDateTime.parse("2010-06-30T01:20:47.999+01:00"), "('2010-06-30T00:20:47.999Z','+01:00')" }
65+ };
66+ }
67+
68+ @Test(groups = "unit", dataProvider = "ZonedDateTimeCodecTest.parse")
69+ public void should_parse_valid_formats(String input, ZonedDateTime expected) {
70+ // given
71+ TupleType tupleType = mock(TupleType.class);
72+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
73+ ZonedDateTimeCodec codec = new ZonedDateTimeCodec(tupleType);
74+ // when
75+ ZonedDateTime actual = codec.parse(input);
76+ // then
77+ assertThat(actual).isEqualTo(expected);
78+ }
79+
80+ @Test(groups = "unit", dataProvider = "ZonedDateTimeCodecTest.format")
81+ public void should_serialize_and_format_valid_object(ZonedDateTime input, String expected) {
82+ // given
83+ when(tupleType.getComponentTypes()).thenReturn(newArrayList(timestamp(), varchar()));
84+ ZonedDateTimeCodec codec = new ZonedDateTimeCodec(tupleType);
85+ // when
86+ String actual = codec.format(input);
87+ // then
88+ Assertions.assertThat(codec).withProtocolVersion(V4).canSerialize(input);
89+ assertThat(actual).isEqualTo(expected);
90+ }
91+
92+}