| 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.mapping; |
| 17 | |
| 18 | import com.datastax.driver.core.*; |
| 19 | import com.datastax.driver.mapping.annotations.Accessor; |
| 20 | import com.datastax.driver.mapping.annotations.Table; |
| 21 | import com.datastax.driver.mapping.annotations.UDT; |
| 22 | import org.slf4j.Logger; |
| 23 | import org.slf4j.LoggerFactory; |
| 24 | |
| 25 | import java.util.*; |
| 26 | |
| 27 | /** |
| 28 | * Mapping manager from which to obtain entity mappers. |
| 29 | */ |
| 30 | public class MappingManager { |
| 31 | |
| 32 | private static final Logger LOGGER = LoggerFactory.getLogger(MappingManager.class); |
| 33 | |
| 34 | private final Session session; |
| 35 | final boolean isCassandraV1; |
| 36 | |
| 37 | private volatile Map<Class<?>, Mapper<?>> mappers = Collections.emptyMap(); |
| 38 | private volatile Map<Class<?>, MappedUDTCodec<?>> udtCodecs = Collections.emptyMap(); |
| 39 | private volatile Map<Class<?>, Object> accessors = Collections.emptyMap(); |
| 40 | |
| 41 | /** |
| 42 | * Creates a new {@code MappingManager} using the provided {@code Session}. |
| 43 | * <p/> |
| 44 | * Note that this constructor forces the initialization of the session (see |
| 45 | * {@link #MappingManager(Session, ProtocolVersion)} if that is a problem for you). |
| 46 | * |
| 47 | * @param session the {@code Session} to use. |
| 48 | */ |
| 49 | public MappingManager(Session session) { |
| 50 | this(session, getProtocolVersion(session)); |
| 51 | } |
| 52 | |
| 53 | private static ProtocolVersion getProtocolVersion(Session session) { |
| 54 | session.init(); |
| 55 | return session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Creates a new {@code MappingManager} using the provided {@code Session}. |
| 60 | * <p/> |
| 61 | * This constructor is only provided for backward compatibility: before 2.1.7, {@code MappingManager} could be |
| 62 | * built from an uninitialized session; since 2.1.7, the mapper needs to know the active protocol version to |
| 63 | * adapt its internal requests, so {@link #MappingManager(Session)} will now initialize the session if needed. |
| 64 | * If you rely on the session not being initialized, use this constructor and provide the version manually. |
| 65 | * |
| 66 | * @param session the {@code Session} to use. |
| 67 | * @param protocolVersion the protocol version that will be used with this session. |
| 68 | * @since 2.1.7 |
| 69 | */ |
| 70 | public MappingManager(Session session, ProtocolVersion protocolVersion) { |
| 71 | this.session = session; |
| 72 | // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol. |
| 73 | // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance |
| 74 | // which nodes might join the cluster later. |
| 75 | // At least if protocol >=2 we know there won't be any 1.2 nodes ever. |
| 76 | this.isCassandraV1 = (protocolVersion == ProtocolVersion.V1); |
| 77 | session.getCluster().register(new SchemaChangeListenerBase() { |
| 78 | |
| 79 | @Override |
| 80 | public void onTableRemoved(TableMetadata table) { |
| 81 | synchronized (mappers) { |
| 82 | Iterator<Mapper<?>> it = mappers.values().iterator(); |
| 83 | while (it.hasNext()) { |
| 84 | Mapper<?> mapper = it.next(); |
| 85 | if (mapper.getTableMetadata().equals(table)) { |
| 86 | LOGGER.error("Table {} has been removed; existing mappers for @Entity annotated {} will not work anymore", table.getName(), mapper.getMappedClass()); |
| 87 | it.remove(); |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | @Override |
| 94 | public void onTableChanged(TableMetadata current, TableMetadata previous) { |
| 95 | synchronized (mappers) { |
| 96 | Iterator<Mapper<?>> it = mappers.values().iterator(); |
| 97 | while (it.hasNext()) { |
| 98 | Mapper<?> mapper = it.next(); |
| 99 | if (mapper.getTableMetadata().equals(previous)) { |
| 100 | LOGGER.warn("Table {} has been altered; existing mappers for @Entity annotated {} might not work properly anymore", |
| 101 | previous.getName(), mapper.getMappedClass()); |
| 102 | it.remove(); |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | @Override |
| 109 | public void onUserTypeRemoved(UserType type) { |
| 110 | synchronized (udtCodecs) { |
| 111 | Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator(); |
| 112 | while (it.hasNext()) { |
| 113 | MappedUDTCodec<?> codec = it.next(); |
| 114 | if (type.equals(codec.getCqlType())) { |
| 115 | LOGGER.error("User type {} has been removed; existing mappers for @UDT annotated {} will not work anymore", |
| 116 | type, codec.getUdtClass()); |
| 117 | it.remove(); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | @Override |
| 124 | public void onUserTypeChanged(UserType current, UserType previous) { |
| 125 | synchronized (udtCodecs) { |
| 126 | Set<Class<?>> udtClasses = new HashSet<Class<?>>(); |
| 127 | Iterator<MappedUDTCodec<?>> it = udtCodecs.values().iterator(); |
| 128 | while (it.hasNext()) { |
| 129 | MappedUDTCodec<?> codec = it.next(); |
| 130 | if (previous.equals(codec.getCqlType())) { |
| 131 | LOGGER.warn("User type {} has been altered; existing mappers for @UDT annotated {} might not work properly anymore", |
| 132 | previous, codec.getUdtClass()); |
| 133 | udtClasses.add(codec.getUdtClass()); |
| 134 | it.remove(); |
| 135 | } |
| 136 | } |
| 137 | for (Class<?> udtClass : udtClasses) { |
| 138 | // try to register an updated version of the previous codec |
| 139 | try { |
| 140 | getUDTCodec(udtClass); |
| 141 | } catch (Exception e) { |
| 142 | LOGGER.error("Could not update mapping for @UDT annotated " + udtClass, e); |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | }); |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * The underlying {@code Session} used by this manager. |
| 153 | * <p/> |
| 154 | * Note that you can get obtain the {@code Cluster} object corresponding |
| 155 | * to that session using {@code getSession().getCluster()}. |
| 156 | * <p/> |
| 157 | * It is inadvisable to close the returned Session while this manager and |
| 158 | * its mappers are in use. |
| 159 | * |
| 160 | * @return the underlying session used by this manager. |
| 161 | */ |
| 162 | public Session getSession() { |
| 163 | return session; |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Creates a {@code Mapper} for the provided class (that must be annotated by a |
| 168 | * {@link Table} annotation). |
| 169 | * <p/> |
| 170 | * The {@code MappingManager} only ever keeps one Mapper for each class, and so calling this |
| 171 | * method multiple times on the same class will always return the same object. |
| 172 | * <p/> |
| 173 | * If the type of any field in the class is an {@link UDT}-annotated classes, a codec for that |
| 174 | * class will automatically be created and registered with the underlying {@code Cluster}. |
| 175 | * This works recursively with UDTs nested in other UDTs or in collections. |
| 176 | * |
| 177 | * @param <T> the type of the class to map. |
| 178 | * @param klass the (annotated) class for which to return the mapper. |
| 179 | * @return the {@code Mapper} object for class {@code klass}. |
| 180 | */ |
| 181 | public <T> Mapper<T> mapper(Class<T> klass) { |
| 182 | return getMapper(klass); |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * Creates a {@code TypeCodec} for the provided class (that must be annotated by |
| 187 | * a {@link UDT} annotation). |
| 188 | * <p/> |
| 189 | * This method also registers the codec against the underlying {@code Cluster}. |
| 190 | * In addition, the codecs for any nested UDTs will also be created and registered. |
| 191 | * <p/> |
| 192 | * You don't need to call this method explicitly if you already call {@link #mapper(Class)} |
| 193 | * for a class that references this UDT class (creating a mapper will automatically |
| 194 | * process all UDTs that it uses). |
| 195 | * |
| 196 | * @param <T> the type of the class to map. |
| 197 | * @param klass the (annotated) class for which to return the codec. |
| 198 | * @return the codec that maps the provided class to the corresponding user-defined type. |
| 199 | */ |
| 200 | public <T> TypeCodec<T> udtCodec(Class<T> klass) { |
| 201 | return getUDTCodec(klass); |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Creates an accessor object based on the provided interface (that must be annotated by |
| 206 | * a {@link Accessor} annotation). |
| 207 | * <p/> |
| 208 | * The {@code MappingManager} only ever keep one Accessor for each class, and so calling this |
| 209 | * method multiple time on the same class will always return the same object. |
| 210 | * |
| 211 | * @param <T> the type of the accessor class. |
| 212 | * @param klass the (annotated) class for which to create an accessor object. |
| 213 | * @return the accessor object for class {@code klass}. |
| 214 | */ |
| 215 | public <T> T createAccessor(Class<T> klass) { |
| 216 | return getAccessor(klass); |
| 217 | } |
| 218 | |
| 219 | @SuppressWarnings("unchecked") |
| 220 | private <T> Mapper<T> getMapper(Class<T> klass) { |
| 221 | Mapper<T> mapper = (Mapper<T>) mappers.get(klass); |
| 222 | if (mapper == null) { |
| 223 | synchronized (mappers) { |
| 224 | mapper = (Mapper<T>) mappers.get(klass); |
| 225 | if (mapper == null) { |
| 226 | EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, this); |
| 227 | mapper = new Mapper<T>(this, klass, entityMapper); |
| 228 | Map<Class<?>, Mapper<?>> newMappers = new HashMap<Class<?>, Mapper<?>>(mappers); |
| 229 | newMappers.put(klass, mapper); |
| 230 | mappers = newMappers; |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | return mapper; |
| 235 | } |
| 236 | |
| 237 | @SuppressWarnings("unchecked") |
| 238 | <T> TypeCodec<T> getUDTCodec(Class<T> mappedClass) { |
| 239 | MappedUDTCodec<T> codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass); |
| 240 | if (codec == null) { |
| 241 | synchronized (udtCodecs) { |
| 242 | codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass); |
| 243 | if (codec == null) { |
| 244 | codec = AnnotationParser.parseUDT(mappedClass, this); |
| 245 | session.getCluster().getConfiguration().getCodecRegistry().register(codec); |
| 246 | |
| 247 | HashMap<Class<?>, MappedUDTCodec<?>> newCodecs = new HashMap<Class<?>, MappedUDTCodec<?>>(udtCodecs); |
| 248 | newCodecs.put(mappedClass, codec); |
| 249 | udtCodecs = newCodecs; |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | return codec; |
| 254 | } |
| 255 | |
| 256 | @SuppressWarnings("unchecked") |
| 257 | private <T> T getAccessor(Class<T> klass) { |
| 258 | T accessor = (T) accessors.get(klass); |
| 259 | if (accessor == null) { |
| 260 | synchronized (accessors) { |
| 261 | accessor = (T) accessors.get(klass); |
| 262 | if (accessor == null) { |
| 263 | AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, this); |
| 264 | mapper.prepare(this); |
| 265 | accessor = mapper.createProxy(); |
| 266 | Map<Class<?>, Object> newAccessors = new HashMap<Class<?>, Object>(accessors); |
| 267 | newAccessors.put(klass, accessor); |
| 268 | accessors = newAccessors; |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | return accessor; |
| 273 | } |
| 274 | } |