com.google.cloud.datastore.StringValue Java Examples

The following examples show how to use com.google.cloud.datastore.StringValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultDatastoreEntityConverterTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void writeTestSubtypes() {
	DiscrimEntityD entityD = new DiscrimEntityD();
	entityD.stringField = "item D";
	entityD.intField = 10;
	entityD.enumField = TestDatastoreItem.Color.BLACK;

	Entity.Builder builder = getEntityBuilder();
	ENTITY_CONVERTER.write(entityD, builder);

	Entity entity = builder.build();


	assertThat(entity.getString("stringField")).as("validate string field").isEqualTo("item D");
	assertThat(entity.getLong("intField")).as("validate int field").isEqualTo(10L);
	assertThat(entity.getString("enumField")).as("validate enum field").isEqualTo("BLACK");
	assertThat(entity.getList("discrimination_column")).as("validate discrimination field")
			.containsExactly(StringValue.of("D"), StringValue.of("B"), StringValue.of("X"));
}
 
Example #2
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private void setUpQueryTests() {
  Key taskKey = datastore.newKeyFactory()
      .setKind("Task")
      .addAncestors(PathElement.of("TaskList", "default"))
      .newKey("someTask");
  datastore.put(Entity.newBuilder(taskKey)
      .set("category", "Personal")
      .set("done", false)
      .set("completed", false)
      .set("priority", 4)
      .set("created", includedDate)
      .set("percent_complete", 10.0)
      .set("description",
          StringValue.newBuilder("Learn Cloud Datastore").setExcludeFromIndexes(true).build())
      .set("tag", "fun", "l", "programming")
      .build());
}
 
Example #3
Source File: DatastoreStorage.java    From styx with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Entity workflowToEntity(Workflow workflow, WorkflowState state, Optional<Entity> existing, Key key)
    throws JsonProcessingException {
  var json = OBJECT_MAPPER.writeValueAsString(workflow);

  var builder = asBuilderOrNew(existing, key)
      .set(PROPERTY_COMPONENT, workflow.componentId())
      .set(PROPERTY_WORKFLOW_JSON, StringValue.newBuilder(json).setExcludeFromIndexes(true).build());

  state.enabled()
      .ifPresent(x -> builder.set(PROPERTY_WORKFLOW_ENABLED, x));
  state.nextNaturalTrigger()
      .ifPresent(x -> builder.set(PROPERTY_NEXT_NATURAL_TRIGGER, instantToTimestamp(x)));
  state.nextNaturalOffsetTrigger()
      .ifPresent(x -> builder.set(PROPERTY_NEXT_NATURAL_OFFSET_TRIGGER, instantToTimestamp(x)));

  return builder.build();
}
 
Example #4
Source File: ZonedDateTimeMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = MappingException.class)
public void testToModel2() {
  StringValue v = StringValue.of("Hello");
  ZonedDateTimeMapper mapper = new ZonedDateTimeMapper();
  try {
    mapper.toModel(v);
  } catch (MappingException e) {
    e.printStackTrace();
    throw e;
  }
}
 
Example #5
Source File: UpperCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_2() {
  Value<?>[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"),
      StringValue.of("thRee") };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<StringValue> inputList = (List<StringValue>) input.get();
  List<StringValue> outputList = (List<StringValue>) output.get();
  assertEquals(inputList.get(0).get().toUpperCase(Locale.ENGLISH), outputList.get(0).get());
  assertEquals(inputList.get(1).get().toUpperCase(Locale.ENGLISH), outputList.get(1).get());
  assertEquals(inputList.get(2).get().toUpperCase(Locale.ENGLISH), outputList.get(2).get());
}
 
Example #6
Source File: UpperCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_3() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of() };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<? extends Value> inputList = input.get();
  List<? extends Value> outputList = output.get();
  assertEquals(((StringValue) inputList.get(0)).get().toUpperCase(Locale.ENGLISH),
      outputList.get(0).get());
  assertEquals(inputList.get(1).get(), outputList.get(1).get());
}
 
Example #7
Source File: UpperCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_4() {
  StringValue input = StringValue.of("Hello World");
  try {
    Value<?> output = indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #8
Source File: UpperCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_5() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  try {
    ListValue output = (ListValue) indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #9
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_2() {
  Value<?>[] inputArray = { StringValue.of("ONE"), StringValue.of("Two"),
      StringValue.of("thRee") };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<StringValue> inputList = (List<StringValue>) input.get();
  List<StringValue> outputList = (List<StringValue>) output.get();
  assertEquals(inputList.get(0).get().toLowerCase(Locale.ENGLISH), outputList.get(0).get());
  assertEquals(inputList.get(1).get().toLowerCase(Locale.ENGLISH), outputList.get(1).get());
  assertEquals(inputList.get(2).get().toLowerCase(Locale.ENGLISH), outputList.get(2).get());
}
 
Example #10
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_3() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of() };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  ListValue output = (ListValue) indexer.index(input);
  List<? extends Value> inputList = input.get();
  List<? extends Value> outputList = output.get();
  assertEquals(((StringValue) inputList.get(0)).get().toLowerCase(Locale.ENGLISH),
      outputList.get(0).get());
  assertEquals(inputList.get(1).get(), outputList.get(1).get());
}
 
Example #11
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_4() {
  StringValue input = StringValue.of("Hello World");
  try {
    Value<?> output = indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #12
Source File: LowerCaseStringListIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexingException.class)
public void testIndex_5() {
  Value<?>[] inputArray = { StringValue.of("Hello"), NullValue.of(), LongValue.of(5L) };
  ListValue input = ListValue.of(Arrays.asList(inputArray));
  try {
    ListValue output = (ListValue) indexer.index(input);
  } catch (Exception exp) {
    LOGGER.log(Level.INFO, exp.toString());
    throw exp;
  }
}
 
Example #13
Source File: DeviceTypeMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  String s = ((DeviceType) input).toString().toLowerCase();
  return StringValue.newBuilder(s);
}
 
Example #14
Source File: DeviceTypeMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  String s = ((StringValue) input).get();
  return Enum.valueOf(DeviceType.class, s.toUpperCase());
}
 
Example #15
Source File: UpperCaseStringIndexerTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndex_2() {
  StringValue input = StringValue.of("Hello World!");
  StringValue output = (StringValue) indexer.index(input);
  assertEquals(input.get().toUpperCase(Locale.ENGLISH), output.get());
  assertNotEquals(input.get(), output.get());
}
 
Example #16
Source File: OffsetDateTimeMapperTest.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Test(expected = MappingException.class)
public void testToModel2() {
  StringValue v = StringValue.of("Hello");
  OffsetDateTimeMapper mapper = new OffsetDateTimeMapper();
  try {
    mapper.toModel(v);
  } catch (MappingException e) {
    e.printStackTrace();
    throw e;
  }
}
 
Example #17
Source File: DatastoreStorageTransaction.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
public Backfill store(Backfill backfill) throws IOException {
  final Key key = DatastoreStorage.backfillKey(tx.getDatastore().newKeyFactory(), backfill.id());
  Entity.Builder builder = Entity.newBuilder(key)
      .set(PROPERTY_CONCURRENCY, backfill.concurrency())
      .set(PROPERTY_START, instantToTimestamp(backfill.start()))
      .set(PROPERTY_END, instantToTimestamp(backfill.end()))
      .set(PROPERTY_COMPONENT, backfill.workflowId().componentId())
      .set(PROPERTY_WORKFLOW, backfill.workflowId().id())
      .set(PROPERTY_SCHEDULE, backfill.schedule().toString())
      .set(PROPERTY_NEXT_TRIGGER, instantToTimestamp(backfill.nextTrigger()))
      .set(PROPERTY_ALL_TRIGGERED, backfill.allTriggered())
      .set(PROPERTY_HALTED, backfill.halted())
      .set(PROPERTY_REVERSE, backfill.reverse());

  backfill.created().ifPresent(x -> builder.set(PROPERTY_CREATED,
      instantToTimestamp(x)));
  backfill.lastModified().ifPresent(x -> builder.set(PROPERTY_LAST_MODIFIED,
      instantToTimestamp(x)));
  backfill.description().ifPresent(x -> builder.set(PROPERTY_DESCRIPTION, StringValue
      .newBuilder(x).setExcludeFromIndexes(true).build()));

  if (backfill.triggerParameters().isPresent()) {
    final String json = OBJECT_MAPPER.writeValueAsString(backfill.triggerParameters().get());
    builder.set(PROPERTY_TRIGGER_PARAMETERS,
        StringValue.newBuilder(json).setExcludeFromIndexes(true).build());
  }

  tx.put(builder.build());

  return backfill;
}
 
Example #18
Source File: DatastoreStorageTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnClientBlacklist() throws IOException {
  Entity config = Entity.newBuilder(DatastoreStorage.globalConfigKey(datastore.newKeyFactory()))
      .set(DatastoreStorage.PROPERTY_CONFIG_CLIENT_BLACKLIST,
          List.of(StringValue.of("v1"), StringValue.of("v2"), StringValue.of("v3")))
      .build();
  datastoreClient.put(config);
  var blacklist = storage.config().clientBlacklist();
  assertThat(blacklist.size(), is(3));
  assertThat(blacklist.contains("v1"), is(true));
  assertThat(blacklist.contains("v2"), is(true));
  assertThat(blacklist.contains("v3"), is(true));
}
 
Example #19
Source File: TaskList.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a task entity to the Datastore.
 *
 * @param description The task description
 * @return The {@link Key} of the entity
 * @throws DatastoreException if the ID allocation or put fails
 */
Key addTask(String description) {
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity task = Entity.newBuilder(key)
      .set("description", StringValue.newBuilder(description).setExcludeFromIndexes(true).build())
      .set("created", Timestamp.now())
      .set("done", false)
      .build();
  datastore.put(task);
  return key;
}
 
Example #20
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testProperties() {
  // [START datastore_properties]
  Entity task = Entity.newBuilder(taskKey)
      .set("category", "Personal")
      .set("created", Timestamp.now())
      .set("done", false)
      .set("priority", 4)
      .set("percent_complete", 10.0)
      .set("description",
        StringValue.newBuilder("Learn Cloud Datastore").setExcludeFromIndexes(true).build())
      .build();
  // [END datastore_properties]
  assertValidEntity(task);
}
 
Example #21
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyByKindRunQuery() {
  setUpQueryTests();
  // [START datastore_property_by_kind_run_query]
  Key key = datastore.newKeyFactory().setKind("__kind__").newKey("Task");
  Query<Entity> query = Query.newEntityQueryBuilder()
      .setKind("__property__")
      .setFilter(PropertyFilter.hasAncestor(key))
      .build();
  QueryResults<Entity> results = datastore.run(query);
  Map<String, Collection<String>> representationsByProperty = new HashMap<>();
  while (results.hasNext()) {
    Entity result = results.next();
    String propertyName = result.getKey().getName();
    List<StringValue> representations = result.getList("property_representation");
    Collection<String> currentRepresentations = representationsByProperty.get(propertyName);
    if (currentRepresentations == null) {
      currentRepresentations = new HashSet<>();
      representationsByProperty.put(propertyName, currentRepresentations);
    }
    for (StringValue value : representations) {
      currentRepresentations.add(value.get());
    }
  }
  // [END datastore_property_by_kind_run_query]
  Map<String, Collection<String>> expected = ImmutableMap.<String, Collection<String>>builder()
      .put("category", Collections.singleton("STRING"))
      .put("done", Collections.singleton("BOOLEAN"))
      .put("completed", Collections.singleton("BOOLEAN"))
      .put("priority", Collections.singleton("INT64"))
      .put("created", Collections.singleton("INT64"))
      .put("percent_complete", Collections.singleton("DOUBLE"))
      .put("tag", Collections.singleton("STRING"))
      .build();
  assertEquals(expected, representationsByProperty);
}
 
Example #22
Source File: CharMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  String str = ((StringValue) input).get();
  if (str.length() != 1) {
    throw new MappingException(String.format("Unable to convert %s to char", str));
  }
  return str.charAt(0);
}
 
Example #23
Source File: DefaultDatastoreEntityConverter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void write(Object source, BaseEntity.Builder sink) {
	DatastorePersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(source.getClass());

	String discriminationFieldName = persistentEntity.getDiscriminationFieldName();
	List<String> discriminationValues = persistentEntity.getCompatibleDiscriminationValues();
	if (!discriminationValues.isEmpty() || discriminationFieldName != null) {
		sink.set(discriminationFieldName,
				discriminationValues.stream().map(StringValue::of).collect(Collectors.toList()));
	}
	PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(source);
	persistentEntity.doWithColumnBackedProperties(
			(DatastorePersistentProperty persistentProperty) -> {
				// Datastore doesn't store its Key as a regular field.
				if (persistentProperty.isIdProperty()) {
					return;
				}
				try {
					Object val = accessor.getProperty(persistentProperty);
					Value convertedVal = this.conversions.convertOnWrite(val, persistentProperty);

					if (persistentProperty.isUnindexed()) {
						convertedVal = setExcludeFromIndexes(convertedVal);
					}
					sink.set(persistentProperty.getFieldName(), convertedVal);
				}
				catch (DatastoreDataException ex) {
					throw new DatastoreDataException(
							"Unable to write "
									+ persistentEntity.kindName() + "." + persistentProperty.getFieldName(),
							ex);
				}
			});
}
 
Example #24
Source File: UpperCaseStringIndexer.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Value<?> index(Value<?> input) {
  if (input.getType() == ValueType.NULL) {
    return NullValue.of();
  }
  try {
    String str = ((StringValue) input).get();
    return StringValue.of(str.toUpperCase(Locale.ENGLISH));
  } catch (Exception exp) {
    throw new IndexingException(exp);
  }
}
 
Example #25
Source File: LowerCaseStringIndexer.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Value<?> index(Value<?> input) {
  if (input.getType() == ValueType.NULL) {
    return NullValue.of();
  }
  try {
    String str = ((StringValue) input).get();
    return StringValue.of(str.toLowerCase(Locale.ENGLISH));
  } catch (Exception exp) {
    throw new IndexingException(exp);
  }
}
 
Example #26
Source File: LocalDateMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  return StringValue.newBuilder(input.toString());
}
 
Example #27
Source File: LocalDateMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  try {
    return LocalDate.parse(((StringValue) input).get());
  } catch (ClassCastException exp) {
    String pattern = "Mapping of type %s to %s is not supported";
    throw new MappingException(
        String.format(pattern, input.getClass().getName(), LocalDate.class.getName()), exp);
  }
}
 
Example #28
Source File: StringMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  return StringValue.newBuilder((String) input);
}
 
Example #29
Source File: StringMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public Object toModel(Value<?> input) {
  if (input instanceof NullValue) {
    return null;
  }
  return ((StringValue) input).get();
}
 
Example #30
Source File: CharMapper.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
@Override
public ValueBuilder<?, ?, ?> toDatastore(Object input) {
  if (input == null) {
    return NullValue.newBuilder();
  }
  return StringValue.newBuilder(String.valueOf((char) input));
}