Elffuss BraidHub

kikocis/java-driver public

1fb5186c7678 · 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 com.datastax.driver.core.*;
19
20import java.nio.ByteBuffer;
21import java.util.*;
22import java.util.Map.Entry;
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 * @throws IllegalArgumentException if the {@code UDTValue} is not of the
56 * type indicated in the mapped class's {@code @UDT} annotation.
57 */
58 public T fromUDT(UDTValue v) {
59 if (!v.getType().equals(userType)) {
60 String message = String.format("UDT conversion mismatch: expected type %s, got %s",
61 userType, v.getType());
62 throw new IllegalArgumentException(message);
63 }
64 return toEntity(v);
65 }
66
67 /**
68 * Converts a mapped class to a {@link UDTValue}.
69 *
70 * @param entity an instance of the mapped class.
71 * @return the corresponding {@code UDTValue}.
72 */
73 public UDTValue toUDT(T entity) {
74 UDTValue udtValue = userType.newValue();
75 for (ColumnMapper<T> cm : entityMapper.allColumns()) {
76 Object value = cm.getValue(entity);
77 udtValue.setBytesUnsafe(cm.getColumnName(), value == null ? null : cm.getDataType().serialize(value, UDT_PROTOCOL_VERSION));
78 }
79 return udtValue;
80 }
81
82 UserType getUserType() {
83 return userType;
84 }
85
86 T toEntity(UDTValue udtValue) {
87 T entity = entityMapper.newEntity();
88 for (ColumnMapper<T> cm : entityMapper.allColumns()) {
89 ByteBuffer bytes = udtValue.getBytesUnsafe(cm.getColumnName());
90 if (bytes != null)
91 cm.setValue(entity, cm.getDataType().deserialize(bytes, UDT_PROTOCOL_VERSION));
92 }
93 return entity;
94 }
95
96 /**
97 * Handles a (possibly nested) collection where some of the elements are domain classes that
98 * must be converted to {@code UDTValue} instances.
99 */
100 @SuppressWarnings("unchecked")
101 static Object convertEntitiesToUDTs(Object value, InferredCQLType type) {
102 if (value == null)
103 return null;
104
105 if (!type.containsMappedUDT)
106 return value;
107
108 if (type.udtMapper != null)
109 return type.udtMapper.toUDT(value);
110
111 if (type.dataType.getName() == DataType.Name.LIST) {
112 InferredCQLType elementType = type.childTypes.get(0);
113 List<Object> result = new ArrayList<Object>();
114 for (Object element : (List<Object>) value)
115 result.add(convertEntitiesToUDTs(element, elementType));
116 return result;
117 }
118
119 if (type.dataType.getName() == DataType.Name.SET) {
120 InferredCQLType elementType = type.childTypes.get(0);
121 Set<Object> result = new LinkedHashSet<Object>();
122 for (Object element : (Set<Object>) value)
123 result.add(convertEntitiesToUDTs(element, elementType));
124 return result;
125 }
126
127 if (type.dataType.getName() == DataType.Name.MAP) {
128 InferredCQLType keyType = type.childTypes.get(0);
129 InferredCQLType valueType = type.childTypes.get(1);
130 Map<Object, Object> result = new LinkedHashMap<Object, Object>();
131 for (Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet())
132 result.put(
133 convertEntitiesToUDTs(entry.getKey(), keyType),
134 convertEntitiesToUDTs(entry.getValue(), valueType)
135 );
136 return result;
137 }
138 throw new IllegalArgumentException("Error converting " + value);
139 }
140
141 /**
142 * Handles a (possibly nested) collection where some of the elements are {@code UDTValue}
143 * instances that must be converted to domain classes.
144 */
145 @SuppressWarnings("unchecked")
146 static Object convertUDTsToEntities(Object value, InferredCQLType type) {
147 if (value == null)
148 return null;
149
150 if (!type.containsMappedUDT)
151 return value;
152
153 if (type.udtMapper != null)
154 return type.udtMapper.toEntity((UDTValue) value);
155
156 if (type.dataType.getName() == DataType.Name.LIST) {
157 InferredCQLType elementType = type.childTypes.get(0);
158 List<Object> result = new ArrayList<Object>();
159 for (Object element : (List<Object>) value)
160 result.add(convertUDTsToEntities(element, elementType));
161 return result;
162 }
163
164 if (type.dataType.getName() == DataType.Name.SET) {
165 InferredCQLType elementType = type.childTypes.get(0);
166 Set<Object> result = new LinkedHashSet<Object>();
167 for (Object element : (Set<Object>) value)
168 result.add(convertUDTsToEntities(element, elementType));
169 return result;
170 }
171
172 if (type.dataType.getName() == DataType.Name.MAP) {
173 InferredCQLType keyType = type.childTypes.get(0);
174 InferredCQLType valueType = type.childTypes.get(1);
175 Map<Object, Object> result = new LinkedHashMap<Object, Object>();
176 for (Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet())
177 result.put(
178 convertUDTsToEntities(entry.getKey(), keyType),
179 convertUDTsToEntities(entry.getValue(), valueType)
180 );
181 return result;
182 }
183 throw new IllegalArgumentException("Error converting " + value);
184 }
185}