/** * 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"); }
public void addProperties(List<UDTValue> properties) { if (properties != null && !properties.isEmpty()) { for (UDTValue value : properties) { Property property = ResourceFactory.createProperty(value.getString("property")); RDFNode propertyValue; if (value.isNull("datatype")) { propertyValue = ResourceFactory.createResource(value.getString("value")); } else { propertyValue = ResourceFactory.createTypedLiteral(value.getString("value"), TypeMapper.getInstance().getSafeTypeByName(value.getString("datatype"))); } addProperty(property, propertyValue); } } }
@Override public Model call(ResultSet resultSet) { Model commandResults = ModelFactory.createDefaultModel(); resultSet.forEach((row) -> { CommandResult commandResult = new CommandResult( row.getString("system_id"), row.getString("process_id"), row.getTimestamp("event_time").toInstant().toString(), row.getString("command_type") ); List<UDTValue> properties = row.getList("command_properties", UDTValue.class); commandResult.addProperties(properties); List<UDTValue> parameters = row.getList("command_parameters", UDTValue.class); commandResult.addParameters(parameters); commandResults.add(commandResult.toRDF()); }); return commandResults; }
@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; }
@Override public <K, V> ImmutableMap<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) { if (isNull(name)) { return ImmutableMap.of(); } final DataType datatype = ctx.getCatalog().getColumnMetadata(tablename, name).getType(); if (UDTValueMapper.isBuildInType(datatype)) { return ImmutableMap.copyOf(getRow().getMap(name, keysClass, valuesClass)); } else { if (UDTValueMapper.isBuildInType(datatype.getTypeArguments().get(0))) { return ctx.getUDTValueMapper().fromUdtValues(datatype.getTypeArguments().get(0), datatype.getTypeArguments().get(1), ImmutableMap.copyOf(getRow().getMap(name, keysClass, UDTValue.class)), keysClass, valuesClass); } else if (UDTValueMapper.isBuildInType(datatype.getTypeArguments().get(1))) { return ctx.getUDTValueMapper().fromUdtValues(datatype.getTypeArguments().get(0), datatype.getTypeArguments().get(1), ImmutableMap.copyOf(getRow().getMap(name, UDTValue.class, valuesClass)), keysClass, valuesClass); } else { return ctx.getUDTValueMapper().fromUdtValues(datatype.getTypeArguments().get(0), datatype.getTypeArguments().get(1), ImmutableMap.copyOf(getRow().getMap(name, UDTValue.class, UDTValue.class)), keysClass, valuesClass); } } }
static Trigger getTrigger(UDTValue value) { int type = value.getInt("type"); switch (type) { case 0: return new SingleExecutionTrigger(value.getLong("trigger_time")); case 1: return new RepeatingTrigger( value.getLong("interval"), value.getLong("delay"), value.getLong("trigger_time"), value.getInt("repeat_count"), value.getInt("execution_count") ); default: throw new IllegalArgumentException("Trigger type [" + type + "] is not supported"); } }
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 void addParameters(List<UDTValue> parameters) { if (parameters != null && !parameters.isEmpty()) { for (UDTValue value : parameters) { Resource parameter = ResourceFactory.createResource(value.getString("for_parameter")); RDFNode parameterValue = ResourceFactory.createTypedLiteral(value.getString("value"), TypeMapper.getInstance().getSafeTypeByName(value.getString("datatype"))); addParameter(parameter, parameterValue); } } }
protected Address toAddress(UDTValue value) { return value == null ? null : new Address( value.getString("city"), value.getString("street"), value.getInt("zip_code"), value.getSet("phones", String.class) ); }
protected UDTValue toUDTValue(Address value) { return value == null ? null : userType.newValue() .setString("street", value.getStreet()) .setInt("zip_code", value.getZip_code()) .setString("city", value.getCity()) .setSet("phones", value.getPhones()); }
protected Statement createUpdateStatement(CassandraPersistenceSession session, EventSubscriptionEntity entity) { Session s = session.getSession(); UDTypeHandler typeHander = session.getTypeHander(EventSubscriptionEntity.class); CassandraSerializer<EventSubscriptionEntity> serializer = session.getSerializer(EventSubscriptionEntity.class); UDTValue value = typeHander.createValue(s); serializer.write(value, entity); return QueryBuilder.update(ProcessInstanceTableHandler.TABLE_NAME) .with(put("event_subscriptions", entity.getId(), value)) .where(eq("id", entity.getProcessInstanceId())); }
protected Statement createUpdateStatement(CassandraPersistenceSession session, ExecutionEntity entity) { Session s = session.getSession(); UDTypeHandler typeHander = session.getTypeHander(ExecutionEntity.class); CassandraSerializer<ExecutionEntity> serializer = session.getSerializer(ExecutionEntity.class); UDTValue value = typeHander.createValue(s); serializer.write(value, entity); return QueryBuilder.update(ProcessInstanceTableHandler.TABLE_NAME) .with(put("executions", entity.getId(), value)) .where(eq("id", entity.getProcessInstanceId())); }
protected Statement createUpdateStatement(CassandraPersistenceSession session, VariableInstanceEntity entity) { Session s = session.getSession(); UDTypeHandler typeHandler = session.getTypeHander(VariableInstanceEntity.class); CassandraSerializer<VariableInstanceEntity> serializer = CassandraPersistenceSession.getSerializer(VariableInstanceEntity.class); UDTValue value = typeHandler.createValue(s); serializer.write(value, entity); return QueryBuilder.update(ProcessInstanceTableHandler.TABLE_NAME) .with(put("variables", entity.getId(), value)) .where(eq("id", entity.getProcessInstanceId())); }
public UDTValue createValue(Session s) { return s.getCluster() .getMetadata() .getKeyspace(s.getLoggedKeyspace()) .getUserType(getTypeName()) .newValue(); }
@Override public UDTValue convert(I in) throws Exception { if (in == null) return null; UDTValue udtValue = userType.newValue(); mapper.mapTo(in, udtValue, null); return udtValue; }
@Override public void set(SettableByIndexData target, UDTValue value) throws Exception { if (value == null) { target.setToNull(index); } else { target.setUDTValue(index, value); } }
@Override public <T> ImmutableSet<T> getSet(String name, Class<T> elementsClass) { if (isNull(name)) { return ImmutableSet.of(); } final DataType datatype = ctx.getCatalog().getColumnMetadata(tablename, name).getType(); if (UDTValueMapper.isBuildInType(datatype)) { return ImmutableSet.copyOf(getRow().getSet(name, elementsClass)); } else { return ctx.getUDTValueMapper().fromUdtValues(datatype.getTypeArguments().get(0), ImmutableSet.copyOf(getRow().getSet(name, UDTValue.class)), elementsClass); } }
@Override public <T> ImmutableList<T> getList(String name, Class<T> elementsClass) { if (isNull(name)) { return ImmutableList.of(); } final DataType datatype = ctx.getCatalog().getColumnMetadata(tablename, name).getType(); if (UDTValueMapper.isBuildInType(datatype)) { return ImmutableList.copyOf(getRow().getList(name, elementsClass)); } else { return ctx.getUDTValueMapper().fromUdtValues(datatype.getTypeArguments().get(0), ImmutableList.copyOf(getRow().getList(name, UDTValue.class)), elementsClass); } }
static UDTValue getTriggerValue(RxSession session, Trigger trigger) { if (trigger instanceof RepeatingTrigger) { return getRepeatingTriggerValue(session, (RepeatingTrigger) trigger); } if (trigger instanceof SingleExecutionTrigger) { return getSingleExecutionTriggerValue(session, (SingleExecutionTrigger) trigger); } throw new IllegalArgumentException(trigger.getClass() + " is not a supported trigger type"); }
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; }
protected UDTValue newUDTValue() { return userType.newValue(); }
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(); }
protected FullName toFullName(UDTValue value) { return value == null ? null : new FullName( value.getString("firstname"), value.getString("lastname")); }
protected UDTValue toUDTValue(FullName value) { return value == null ? null : userType.newValue() .setString("lastname", value.getLastname()) .setString("firstname", value.getFirstname()); }
public LoadedCompositeEntity getEntityById(CassandraPersistenceSession session, String id) { LoadedCompositeEntity loadedProcessInstance = new LoadedCompositeEntity(); Session s = session.getSession(); Row row = s.execute(select().all().from(TABLE_NAME).where(eq("id", id))).one(); if(row == null) { return null; } int version = row.getInt("version"); String businessKey = row.getString("business_key"); CassandraSerializer<ExecutionEntity> executionSerializer = session.getSerializer(ExecutionEntity.class); CassandraSerializer<EventSubscriptionEntity> eventSubscriptionSerializer = session.getSerializer(EventSubscriptionEntity.class); CassandraSerializer<VariableInstanceEntity> variableSerializer = session.getSerializer(VariableInstanceEntity.class); // deserialize all executions Map<String, UDTValue> executionsMap = row.getMap(EXECUTIONS, String.class, UDTValue.class); Map<String, ExecutionEntity> executions = new HashMap<String, ExecutionEntity>(); for (UDTValue serializedExecution : executionsMap.values()) { ExecutionEntity executionEntity = executionSerializer.read(serializedExecution); executions.put(executionEntity.getId(), executionEntity); if(executionEntity.isProcessInstanceExecution()) { loadedProcessInstance.setMainEntity(executionEntity); } } loadedProcessInstance.put(EXECUTIONS, executions); // deserialize all event subscription Map<String, UDTValue> eventSubscriptionsMap = row.getMap(EVENT_SUBSCRIPTIONS, String.class, UDTValue.class); Map<String, EventSubscriptionEntity> eventSubscriptions = new HashMap<String, EventSubscriptionEntity>(); for (UDTValue serializedEventSubscription : eventSubscriptionsMap.values()) { EventSubscriptionEntity eventSubscriptionEntity = eventSubscriptionSerializer.read(serializedEventSubscription); eventSubscriptions.put(eventSubscriptionEntity.getId(), eventSubscriptionEntity); } loadedProcessInstance.put(EVENT_SUBSCRIPTIONS, eventSubscriptions); // deserialize all variables Map<String, UDTValue> variablesMap = row.getMap(VARIABLES, String.class, UDTValue.class); Map<String, VariableInstanceEntity> variables = new HashMap<String, VariableInstanceEntity>(); for (UDTValue serializedVariable : variablesMap.values()) { VariableInstanceEntity variableEntity = variableSerializer.read(serializedVariable); variables.put(variableEntity.getId(), variableEntity); } loadedProcessInstance.put(VARIABLES, variables); reconstructEntityTree(loadedProcessInstance); ExecutionEntity processInstance= (ExecutionEntity) loadedProcessInstance.getPrimaryEntity(); processInstance.setRevision(version); processInstance.setBusinessKey(businessKey); ProcessInstanceBatch batch = new ProcessInstanceBatch((ExecutionEntity) loadedProcessInstance.getPrimaryEntity()); LOG.fine("Loaded process instance, id="+processInstance.getId()+", version="+processInstance.getRevision()); session.addLockedBatch(loadedProcessInstance.getPrimaryEntity().getId(), batch); return loadedProcessInstance; }
public UDTValue getUDTValue(int i) { return null; }
public UDTValue getUDTValue(String name) { return null; }
public Class<UDTValue> getType() { return UDTValue.class; }
public UDTValue compose(Object obj) { return (UDTValue)obj; }
public Object decompose(UDTValue value) { return (Object) value; }
@Override public int getScale(UDTValue obj) { // TODO Auto-generated method stub return -1; }
@Override public int getPrecision(UDTValue obj) { // TODO Auto-generated method stub return -1; }
@Override public String toString(UDTValue obj) { // TODO Auto-generated method stub return obj.toString(); }
@Override public UDTValue getUDTValue(int i) { return row.getUDTValue(i); }
@Override public UDTValue getUDTValue(String name) { return row.getUDTValue(name); }
public static Class<?> asJavaClass(DataType.Name name) { if (name == null) return null; switch (name) { case ASCII: return String.class; case BIGINT: return Long.class; case BLOB: return ByteBuffer.class; case BOOLEAN: return Boolean.class; case COUNTER: return Long.class; case DECIMAL: return BigDecimal.class; case DOUBLE: return Double.class; case FLOAT: return Float.class; case INET: return InetAddress.class; case INT: return Integer.class; case LIST: return List.class; case MAP: return Map.class; case SET: return Set.class; case TEXT: return String.class; case TIMESTAMP: return Date.class; case TIMEUUID: return UUID.class; case UUID: return UUID.class; case VARCHAR: return String.class; case VARINT: return BigInteger.class; case UDT: return UDTValue.class; case TUPLE: return TupleValue.class; case CUSTOM: return ByteBuffer.class; } if (isDate(name)) return localDateClass; if (isTime(name)) return Long.class; if (isSmallInt(name)) return Short.class; if (isTinyInt(name)) return Byte.class; return null; }
public ConverterToUDTValueMapper(Mapper<I, UDTValue> mapper, UserType userType) { this.mapper = mapper; this.userType = userType; }