Elffuss BraidHub

kikocis/java-driver public

2ec008046b58 · 7.0 KiBRawPermalink
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 */
16package com.datastax.driver.mapping;
17
18import java.nio.ByteBuffer;
19import java.util.*;
20import java.util.Map.Entry;
21
22import com.datastax.driver.core.*;
23
24/**
25 * An object handling the mapping of a particular class to a UDT.
26 * <p>
27 * A {@code UDTMapper} object is obtained from a {@code MappingManager} using the
28 * {@link MappingManager#udtMapper} method.
29 * </p>
30 */
31public class UDTMapper<T> {
32 // UDTs are always serialized with the v3 protocol
33 private static final ProtocolVersion UDT_PROTOCOL_VERSION = ProtocolVersion.V3;
34
35 private final EntityMapper<T> entityMapper;
36 private final UserType userType;
37
38 UDTMapper(EntityMapper<T> entityMapper, Session session) {
39 this.entityMapper = entityMapper;
40
41 String keyspace = entityMapper.getKeyspace();
42 String udt = entityMapper.getTable();
43 userType = session.getCluster().getMetadata().getKeyspace(keyspace).getUserType(udt);
44 if (userType == null) {
45 throw new IllegalArgumentException(String.format("Type \"%s\" does not exist in keyspace \"%s\"", udt, keyspace));
46 }
47 }
48
49 /**
50 * Converts a {@link UDTValue} (returned by the core API) to the mapped
51 * class.
52 *
53 * @param v the {@code UDTValue}.
54 * @return an instance of the mapped class.
55 *
56 * @throws IllegalArgumentException if the {@code UDTValue} is not of the
57 * type indicated in the mapped class's {@code @UDT} annotation.
58 */
59 public T fromUDT(UDTValue v) {
60 if (!v.getType().equals(userType)) {
61 String message = String.format("UDT conversion mismatch: expected type %s, got %s",
62 userType, v.getType());
63 throw new IllegalArgumentException(message);
64 }
65 return toEntity(v);
66 }
67
68 /**
69 * Converts a mapped class to a {@link UDTValue}.
70 *
71 * @param entity an instance of the mapped class.
72 *
73 * @return the corresponding {@code UDTValue}.
74 */
75 public UDTValue toUDT(T entity) {
76 UDTValue udtValue = userType.newValue();
77 for (ColumnMapper<T> cm : entityMapper.allColumns()) {
78 Object value = cm.getValue(entity);
79 udtValue.setBytesUnsafe(cm.getColumnName(), value == null ? null : cm.getDataType().serialize(value, UDT_PROTOCOL_VERSION));
80 }
81 return udtValue;
82 }
83
84 UserType getUserType() {
85 return userType;
86 }
87
88 T toEntity(UDTValue udtValue) {
89 T entity = entityMapper.newEntity();
90 for (ColumnMapper<T> cm : entityMapper.allColumns()) {
91 ByteBuffer bytes = udtValue.getBytesUnsafe(cm.getColumnName());
92 if (bytes != null)
93 cm.setValue(entity, cm.getDataType().deserialize(bytes, UDT_PROTOCOL_VERSION));
94 }
95 return entity;
96 }
97
98 /**
99 * Handles a (possibly nested) collection where some of the elements are domain classes that
100 * must be converted to {@code UDTValue} instances.
101 */
102 @SuppressWarnings("unchecked")
103 static Object convertEntitiesToUDTs(Object value, InferredCQLType type) {
104 if (value == null)
105 return null;
106
107 if (!type.containsMappedUDT)
108 return value;
109
110 if (type.udtMapper != null)
111 return type.udtMapper.toUDT(value);
112
113 if (type.dataType.getName() == DataType.Name.LIST) {
114 InferredCQLType elementType = type.childTypes.get(0);
115 List<Object> result = new ArrayList<Object>();
116 for (Object element : (List<Object>)value)
117 result.add(convertEntitiesToUDTs(element, elementType));
118 return result;
119 }
120
121 if (type.dataType.getName() == DataType.Name.SET) {
122 InferredCQLType elementType = type.childTypes.get(0);
123 Set<Object> result = new LinkedHashSet<Object>();
124 for (Object element : (Set<Object>)value)
125 result.add(convertEntitiesToUDTs(element, elementType));
126 return result;
127 }
128
129 if (type.dataType.getName() == DataType.Name.MAP) {
130 InferredCQLType keyType = type.childTypes.get(0);
131 InferredCQLType valueType = type.childTypes.get(1);
132 Map<Object, Object> result = new LinkedHashMap<Object, Object>();
133 for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
134 result.put(
135 convertEntitiesToUDTs(entry.getKey(), keyType),
136 convertEntitiesToUDTs(entry.getValue(), valueType)
137 );
138 return result;
139 }
140 throw new IllegalArgumentException("Error converting " + value);
141 }
142
143 /**
144 * Handles a (possibly nested) collection where some of the elements are {@code UDTValue}
145 * instances that must be converted to domain classes.
146 */
147 @SuppressWarnings("unchecked")
148 static Object convertUDTsToEntities(Object value, InferredCQLType type) {
149 if (value == null)
150 return null;
151
152 if (!type.containsMappedUDT)
153 return value;
154
155 if (type.udtMapper != null)
156 return type.udtMapper.toEntity((UDTValue)value);
157
158 if (type.dataType.getName() == DataType.Name.LIST) {
159 InferredCQLType elementType = type.childTypes.get(0);
160 List<Object> result = new ArrayList<Object>();
161 for (Object element : (List<Object>)value)
162 result.add(convertUDTsToEntities(element, elementType));
163 return result;
164 }
165
166 if (type.dataType.getName() == DataType.Name.SET) {
167 InferredCQLType elementType = type.childTypes.get(0);
168 Set<Object> result = new LinkedHashSet<Object>();
169 for (Object element : (Set<Object>)value)
170 result.add(convertUDTsToEntities(element, elementType));
171 return result;
172 }
173
174 if (type.dataType.getName() == DataType.Name.MAP) {
175 InferredCQLType keyType = type.childTypes.get(0);
176 InferredCQLType valueType = type.childTypes.get(1);
177 Map<Object, Object> result = new LinkedHashMap<Object, Object>();
178 for (Entry<Object, Object> entry : ((Map<Object, Object>)value).entrySet())
179 result.put(
180 convertUDTsToEntities(entry.getKey(), keyType),
181 convertUDTsToEntities(entry.getValue(), valueType)
182 );
183 return result;
184 }
185 throw new IllegalArgumentException("Error converting " + value);
186 }
187}