/** * Insert a row with a raw User-defined type. */ @Test public void insertRawUdt() { KeyspaceMetadata keyspaceMetadata = adminOperations.getKeyspaceMetadata(); UserType address = keyspaceMetadata.getUserType("address"); UDTValue udtValue = address.newValue(); udtValue.setString("street", "308 Negra Arroyo Lane"); udtValue.setString("zip", "87104"); udtValue.setString("city", "Albuquerque"); Person person = new Person(); person.setId(42); person.setFirstname("Walter"); person.setLastname("White"); person.setAlternative(udtValue); operations.insert(person); Person loaded = operations.selectOne("SELECT * FROM person WHERE id = 42", Person.class); assertThat(loaded.getAlternative().getString("zip")).isEqualTo("87104"); }
@Override public Map<String, TypeCodec> getCodecsForUserDefinedTypes() { Map<String, TypeCodec> allCodecs = new HashMap<>(); CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry(); UserType addressType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName()) .getUserType("address"); TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType); AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class); allCodecs.put("currentaddress", addressCodec); UserType userFullNameType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName()) .getUserType("fullname"); TypeCodec<UDTValue> userFullNameTypeCodec = codecRegistry.codecFor(userFullNameType); FullNameCodec fullNameCodec = new FullNameCodec(userFullNameTypeCodec, FullName.class); allCodecs.put("username", fullNameCodec); return allCodecs; }
/** * Kicks off table generation. * * @param userTypes the cassandra Udt meta data * @throws IOException if write to file fails */ public static void generate(Collection<UserType> userTypes) throws IOException { String namespaceToUse = MetaData.instance.getUdtNamespace(); for (UserType userType : userTypes) { String rawName = userType.getTypeName(); String name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, rawName); TypeSpec.Builder udtClassBuilder = TypeSpec.classBuilder(name) .addModifiers(Modifier.PUBLIC) .addAnnotation(getUDTAnnotation(userType.getKeyspace(), rawName)); addFields(udtClassBuilder, userType, name); udtClassBuilder.addJavadoc(GeneratorHelper.getJavaDocHeader("UDT class for Cassandra - " + rawName, MetaData.instance.getUpdateTime())); JavaFile javaFile = JavaFile.builder(namespaceToUse, udtClassBuilder.build()).build(); Disk.outputFile(javaFile); } }
/** * Handle getting the class names for parameterized types. * * @param type the cassandra data type to extract from * @return the parameterized type result */ public static TypeResult getClassWithTypes(DataType type) { ClassName outer = getRawType(type); List<TypeName> generics = new ArrayList<>(); boolean hasFrozenType = false; for(DataType genericType : type.getTypeArguments()) { if(Udt.instance.isUdt(genericType)) { generics.add(MetaData.getClassNameForUdt((UserType) genericType)); if(genericType.isFrozen()) { hasFrozenType = true; } } else { generics.add(getRawType(genericType).box()); } } return new TypeResult(ParameterizedTypeName.get(outer, generics.toArray(new TypeName[generics.size()])), hasFrozenType); }
/** * Get a setter spec for a entity field. * * @param field the field name * @param type the cassandra field type * @return the setter method spec */ public static MethodSpec getSetter(String field, DataType type) { String methodRoot = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field); String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field); MethodSpec.Builder spec; if (type.getTypeArguments().size() == 0) { if(Udt.instance.isUdt(type)) { spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(MetaData.getClassNameForUdt((UserType) type), paramName); } else { spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(getRawType(type), paramName); } } else { TypeResult result = getClassWithTypes(type); spec = MethodSpec.methodBuilder("set" + methodRoot).addParameter(result.type, paramName); } spec.addModifiers(Modifier.PUBLIC).addStatement("this.$L = $L", paramName, paramName); return spec.build(); }
/** * Get a getter spec for a entity field. * * @param field the field name * @param type the cassandra field type * @return the getter method spec */ public static MethodSpec getGetter(String field, DataType type) { String methodRoot = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field); String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field); MethodSpec.Builder spec; if (type.getTypeArguments().size() == 0) { if(Udt.instance.isUdt(type)) { spec = MethodSpec.methodBuilder("get" + methodRoot).returns(MetaData.getClassNameForUdt((UserType) type)); } else { spec = MethodSpec.methodBuilder("get" + methodRoot).returns(getRawType(type)); } } else { TypeResult result = getClassWithTypes(type); spec = MethodSpec.methodBuilder("get" + methodRoot).returns(result.type); } spec.addModifiers(Modifier.PUBLIC).addStatement("return $L", paramName); return spec.build(); }
static UDTValue getRepeatingTriggerValue(RxSession session, RepeatingTrigger trigger) { UserType triggerType = getKeyspace(session).getUserType("trigger_def"); UDTValue triggerUDT = triggerType.newValue(); triggerUDT.setInt("type", 1); triggerUDT.setLong("interval", trigger.getInterval()); triggerUDT.setLong("trigger_time", trigger.getTriggerTime()); if (trigger.getDelay() > 0) { triggerUDT.setLong("delay", trigger.getDelay()); } if (trigger.getRepeatCount() != null) { triggerUDT.setInt("repeat_count", trigger.getRepeatCount()); triggerUDT.setInt("execution_count", trigger.getExecutionCount()); } return triggerUDT; }
@SuppressWarnings("unchecked") private UDTValue convertValue(Object value, CassandraEntityMapper<?> mapper, CassandraClient cassandraClient) { String keyspace = cassandraClient.getSession().getLoggedKeyspace(); UserType userType = cassandraClient.getSession() .getCluster() .getMetadata() .getKeyspace(keyspace) .getUserType(mapper.getName()); UDTValue udtValue = userType.newValue(); for (String name : mapper.getNonKeyColumnNames()) { Object fieldValue = mapper.getColumnValueForName(name, value, cassandraClient); if (fieldValue != null) { udtValue.set(name, fieldValue, (Class<Object>) fieldValue.getClass()); } else { udtValue.setToNull(name); } } return udtValue; }
public boolean isUdt(String name) { boolean is = false; for(UserType type : keyspaceMetadata.getUserTypes()) { if (name.toLowerCase().equals(type.getTypeName().toLowerCase())) { is = true; break; } } return is; }
/** * Add fields to the class spec. */ private static void addFields(TypeSpec.Builder builder, UserType userType, String className) { List<String> fields = new ArrayList<>(); for (String field : userType.getFieldNames()) { DataType type = userType.getFieldType(field); builder.addField(EntityGeneratorHelper.getFieldSpec(field, type, true)); builder.addMethod(EntityGeneratorHelper.getSetter(field, type)); builder.addMethod(EntityGeneratorHelper.getGetter(field, type)); fields.add(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field)); } builder.addMethod(EntityGeneratorHelper.getToString(fields, className)); }
/** * Get a FieldSpec for an entity field. * * @param field the field name * @param type the field type * @param isUdtClass is this a UDT entity? * @param extraAnnotations additional annotations to put on the field * @return the FieldSpec representing the cassandra field */ public static FieldSpec getFieldSpec(String field, DataType type, boolean isUdtClass, List<AnnotationSpec> extraAnnotations) { String fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field); FieldSpec.Builder spec; boolean hasFrozen = type.isFrozen(); if (type.getTypeArguments().size() == 0) { if(Udt.instance.isUdt(type)) { spec = FieldSpec.builder(MetaData.getClassNameForUdt((UserType)type), fieldName, Modifier.PUBLIC); } else { spec = FieldSpec.builder(getRawType(type), fieldName, Modifier.PUBLIC); } } else { TypeResult result = getClassWithTypes(type); hasFrozen |= result.hasFrozenType; spec = FieldSpec.builder(result.type, fieldName, Modifier.PUBLIC); } if(hasFrozen) { spec.addAnnotation(getFrozenValueAnnotation()); } if (isUdtClass) { spec.addAnnotation(getFieldAnnotation(field)); } else { spec.addAnnotation(getColumnAnnotation(field)); } spec.addAnnotation(MetaData.getJsonAnnotation(field)); for(AnnotationSpec annotationSpec : extraAnnotations) { spec.addAnnotation(annotationSpec); } return spec.build(); }
public Map<String, Class<?>> getTypeMap() throws SQLException { HashMap<String, Class<?>> typeMap = new HashMap<String, Class<?>>(); logger.info("current KS : " + currentKeyspace); Collection<UserType> types = this.metadata.getKeyspace(currentKeyspace).getUserTypes(); for(UserType type:types){ typeMap.put(type.getTypeName(), type.getClass()); } return typeMap; }
private void loadUserTypes(Collection<UserType> udts, String ksname) { List<UserType> notLoaded = new ArrayList<>(udts); while (!notLoaded.isEmpty()) { Iterator<UserType> i = notLoaded.iterator(); int n = 0; Types.Builder types = Types.builder(); while (i.hasNext()) { try { UserType ut = i.next(); ArrayList<ByteBuffer> fieldNames = new ArrayList<ByteBuffer>(ut.getFieldNames().size()); ArrayList<AbstractType<?>> fieldTypes = new ArrayList<AbstractType<?>>(); for (UserType.Field f : ut) { fieldNames.add(ByteBufferUtil.bytes(f.getName())); fieldTypes.add(getCql3Type(f.getType()).prepare(ksname).getType()); } types = types.add(new org.apache.cassandra.db.marshal.UserType(ksname, ByteBufferUtil.bytes(ut.getTypeName()), fieldNames, fieldTypes)); i.remove(); ++n; } catch (Exception e) { // try again. } } if (n == 0) { throw new RuntimeException("Unable to load user types " + notLoaded); } types.build().forEach(Schema.instance::addType); } }
private static CQL3Type.Raw getCql3Type(DataType dt) throws Exception { CQL3Type.Raw type; switch (dt.getName()) { case LIST: type = CQL3Type.Raw.list(getCql3Type(dt.getTypeArguments().get(0))); break; case MAP: type = CQL3Type.Raw.map(getCql3Type(dt.getTypeArguments().get(0)), getCql3Type(dt.getTypeArguments().get(1))); break; case SET: type = CQL3Type.Raw.set(getCql3Type(dt.getTypeArguments().get(0))); break; case TUPLE: ArrayList<CQL3Type.Raw> tupleTypes = new ArrayList<CQL3Type.Raw>(); for (DataType arg : ((TupleType) dt).getComponentTypes()) { tupleTypes.add(getCql3Type(arg)); } type = CQL3Type.Raw.tuple(tupleTypes); break; case UDT: // Requires this UDT to already be loaded UserType udt = (UserType) dt; type = CQL3Type.Raw.userType(new UTName(new ColumnIdentifier(udt.getKeyspace(), true), new ColumnIdentifier(udt.getTypeName(), true))); break; default: type = CQL3Type.Raw.from( Enum.<CQL3Type.Native> valueOf(CQL3Type.Native.class, dt.getName().toString().toUpperCase())); break; } if (dt.isFrozen()) { type = CQL3Type.Raw.frozen(type); } return type; }
public static <P> Mapper<GettableByIndexData, P> newUDTMapper(Type target, UserType tt, DatastaxMapperFactory factory) { ConstantSourceMapperBuilder<GettableByIndexData, P, DatastaxColumnKey> builder = newFieldMapperBuilder(factory, target); Iterator<UserType.Field> iterator = tt.iterator(); int i = 0; while(iterator.hasNext()) { UserType.Field f = iterator.next(); FieldMapperColumnDefinition<DatastaxColumnKey> identity = FieldMapperColumnDefinition.identity(); builder.addMapping(new DatastaxColumnKey(f.getName(), i, f.getType()), identity); i ++; } return builder.mapper(); }
public UserType get(Tablename tablename, String usertypeName) { final String key = tablename.getKeyspacename() + "." + usertypeName; UserType userType = userTypeCache.getIfPresent(key); if (userType == null) { userType = session.getCluster().getMetadata().getKeyspace(tablename.getKeyspacename()).getUserType(usertypeName); userTypeCache.put(key, userType); } return userType; }
static UDTValue getSingleExecutionTriggerValue(RxSession session, SingleExecutionTrigger trigger) { UserType triggerType = getKeyspace(session).getUserType("trigger_def"); UDTValue triggerUDT = triggerType.newValue(); triggerUDT.setInt("type", 0); triggerUDT.setLong("trigger_time", trigger.getTriggerTime()); return triggerUDT; }
public UDTCodec(TypeCodec<UDTValue> innerCodec, Class<T> javaType) { super(innerCodec.getCqlType(), javaType); this.innerCodec = innerCodec; this.userType = (UserType) innerCodec.getCqlType(); this.javaType = javaType; }
public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType) { super(innerCodec.getCqlType(), javaType); this.innerCodec = innerCodec; this.userType = (UserType)innerCodec.getCqlType(); }
public FullNameCodec(TypeCodec<UDTValue> innerCodec, Class<FullName> javaType) { super(innerCodec.getCqlType(), javaType); this.innerCodec = innerCodec; this.userType = (UserType)innerCodec.getCqlType(); }
public static ClassName getClassNameForUdt(UserType type) { return ClassName.get(MetaData.instance.getUdtNamespace(), Udt.instance.getUdtClassName(type.getTypeName())); }
@SuppressWarnings("unchecked") public static <P> Getter<GettableByIndexData, P> newInstance(DatastaxMapperFactory factory, Type target, UserType tt, int index) { Mapper<GettableByIndexData, P> mapper = newUDTMapper(target, tt, factory); return new DatastaxUDTGetter<P>(mapper, index); }
public ConverterToUDTValueMapper(Mapper<I, UDTValue> mapper, UserType userType) { this.mapper = mapper; this.userType = userType; }
public UserType getUserType(String name) { return keyspaceMetadata.getUserType(name); }
public Collection<UserType> getUserTypes() { return keyspaceMetadata.getUserTypes(); }
public UserTypeCache(Session session) { this.session = session; this.userTypeCache = CacheBuilder.newBuilder().maximumSize(100).<String, UserType>build(); }
protected UserType getUserType(String userType) { return getSession().getCluster().getMetadata().getKeyspace(KAA).getUserType(userType); }
/** * @param tablename the tablename * @param usertypeName the usertype name * @return the usertype */ public UserType getUserType(Tablename tablename, String usertypeName) { return userTypeCache.get(tablename, usertypeName); }
@Override public void onUserTypeAdded(UserType type) { }
@Override public void onUserTypeRemoved(UserType type) { }
@Override public void onUserTypeChanged(UserType current, UserType previous) { }
public UserType getUserType(String name) throws CEUException;
public Collection<UserType> getUserTypes() throws CEUException;
@Override public void onUserTypeAdded(UserType userType) {}
@Override public void onUserTypeRemoved(UserType userType) {}
@Override public void onUserTypeChanged(UserType userType, UserType userType1) {}