graphql.language.Value Java Examples

The following examples show how to use graphql.language.Value. 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: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<InputValueDefinition> createInputValueDefinitions(List<Map<String, Object>> args) {
    List<InputValueDefinition> result = new ArrayList<>();
    for (Map<String, Object> arg : args) {
        Type argType = createTypeIndirection((Map<String, Object>) arg.get("type"));
        String valueLiteral = (String) arg.get("defaultValue");
        Value defaultValue = valueLiteral != null ? AstValueHelper.valueFromAst(valueLiteral) : null;
        InputValueDefinition inputValueDefinition = InputValueDefinition.newInputValueDefinition()
                .name((String) arg.get("name"))
                .type(argType)
                .description(getDescription(arg))
                .defaultValue(defaultValue)
                .build();
        result.add(inputValueDefinition);
    }
    return result;
}
 
Example #2
Source File: GsonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement parseLiteral(Object input) {
    if (input instanceof ObjectValue || input instanceof ArrayValue) {
        throw literalParsingException(input, StringValue.class, BooleanValue.class, EnumValue.class,
                FloatValue.class, IntValue.class, NullValue.class);
    }
    return parseJsonValue(((Value) input));
}
 
Example #3
Source File: ContentTypeBasedDataFetcher.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extracts a scalar value, this is needed because of GraphQL strict types
 */
protected Object getRealValue(Value value, DataFetchingEnvironment env) {
    if (value instanceof BooleanValue) {
        return ((BooleanValue)value).isValue();
    } else if (value instanceof FloatValue) {
        return ((FloatValue) value).getValue();
    } else if (value instanceof IntValue) {
        return ((IntValue) value).getValue();
    } else if (value instanceof StringValue) {
        return ((StringValue) value).getValue();
    } else if (value instanceof VariableReference) {
        return env.getVariables().get(((VariableReference) value).getName());
    }
    return null;
}
 
Example #4
Source File: Scalars.java    From notification with Apache License 2.0 5 votes vote down vote up
public static String errorMessage(Object input, Class<?>... allowedTypes) {
  String types =
      Arrays.stream(allowedTypes)
          .map(type -> "'" + type.getSimpleName() + "'")
          .collect(Collectors.joining(" or "));
  return String.format(
      "Expected %stype %s but was '%s'",
      input instanceof Value ? "AST " : "",
      types,
      input == null ? "null" : input.getClass().getSimpleName());
}
 
Example #5
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static String errorMessage(Object input, Class... allowedTypes) {
    String types = Arrays.stream(allowedTypes)
            .map(type -> "'" + type.getSimpleName() + "'")
            .collect(Collectors.joining(" or "));
    return String.format("Expected %stype %s but was '%s'", input instanceof Value ? "AST " : "",
            types, input == null ? "null" : input.getClass().getSimpleName());
}
 
Example #6
Source File: JacksonObjectScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static JsonNode parseJsonValue(Value value, Map<String, Object> variables) {
    if (value instanceof BooleanValue) {
        return JsonNodeFactory.instance.booleanNode(((BooleanValue) value).isValue());
    }
    if (value instanceof EnumValue) {
        return JsonNodeFactory.instance.textNode(((EnumValue) value).getName());
    }
    if (value instanceof FloatValue) {
        return JsonNodeFactory.instance.numberNode(((FloatValue) value).getValue());
    }
    if (value instanceof IntValue) {
        return JsonNodeFactory.instance.numberNode(((IntValue) value).getValue());
    }
    if (value instanceof NullValue) {
        return JsonNodeFactory.instance.nullNode();
    }
    if (value instanceof StringValue) {
        return JsonNodeFactory.instance.textNode(((StringValue) value).getValue());
    }
    if (value instanceof ArrayValue) {
        List<Value> values = ((ArrayValue) value).getValues();
        ArrayNode jsonArray = JsonNodeFactory.instance.arrayNode(values.size());
        values.forEach(v -> jsonArray.add(parseJsonValue(v, variables)));
        return jsonArray;
    }
    if (value instanceof VariableReference) {
        return OBJECT_MAPPER.convertValue(variables.get(((VariableReference) value).getName()), JsonNode.class);
    }
    if (value instanceof ObjectValue) {
        final ObjectNode result = JsonNodeFactory.instance.objectNode();
        ((ObjectValue) value).getObjectFields().forEach(objectField ->
                result.set(objectField.getName(), parseJsonValue(objectField.getValue(), variables)));
        return result;
    }
    //Should never happen
    throw new CoercingParseLiteralException("Unknown scalar AST type: " + value.getClass().getName());
}
 
Example #7
Source File: GsonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static JsonElement parseJsonValue(Value value) {
    if (value instanceof BooleanValue) {
        return new JsonPrimitive(((BooleanValue) value).isValue());
    }
    if (value instanceof EnumValue) {
        return new JsonPrimitive(((EnumValue) value).getName());
    }
    if (value instanceof FloatValue) {
        return new JsonPrimitive(((FloatValue) value).getValue());
    }
    if (value instanceof IntValue) {
        return new JsonPrimitive(((IntValue) value).getValue());
    }
    if (value instanceof NullValue) {
        return JsonNull.INSTANCE;
    }
    if (value instanceof StringValue) {
        return new JsonPrimitive(((StringValue) value).getValue());
    }
    if (value instanceof ArrayValue) {
        List<Value> values = ((ArrayValue) value).getValues();
        JsonArray jsonArray = new JsonArray(values.size());
        values.forEach(v -> jsonArray.add(parseJsonValue(v)));
        return jsonArray;
    }
    if (value instanceof ObjectValue) {
        final JsonObject result = new JsonObject();
        ((ObjectValue) value).getObjectFields().forEach(objectField ->
                result.add(objectField.getName(), parseJsonValue(objectField.getValue())));
        return result;
    }
    //Should never happen, as it would mean the variable was not replaced by the parser
    throw new CoercingParseLiteralException("Unknown scalar AST type: " + value.getClass().getName());
}
 
Example #8
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Type<?> type(Argument argument) {
    Value<?> value = argument.getValue();
    if (value instanceof VariableReference)
        return resolve(((VariableReference) value).getName());
    throw new GraphQlGeneratorException(
            "unsupported type " + value + " for argument '" + argument.getName() + "'");
}
 
Example #9
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
@Test
public void objectValue() {
  Value value = ObjectValue.newObjectValue()
      .objectField(ObjectField.newObjectField()
          .name("a")
          .value(StringValue.newStringValue("b").build())
          .build())
      .build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is(Map.of("a", "b")));
}
 
Example #10
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
@Test
public void arrayValue() {
  Value value = ArrayValue.newArrayValue()
      .value(StringValue.newStringValue("a").build())
      .build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is(List.of("a")));
}
 
Example #11
Source File: ObjectNodeCoercingTest.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
@Test
public void parseLiteral() {
  Value input = ObjectValue.newObjectValue()
      .objectField(ObjectField.newObjectField()
          .name("a")
          .value(StringValue.newStringValue("b").build())
          .build())
      .build();

  ObjectNodeCoercing spy = Mockito.spy(underTest);
  Object parsed = new Object();
  when(spy.parseLiteral(input, emptyMap())).thenReturn(parsed);
  Object result = spy.parseLiteral(input);
  assertThat(result, is(sameInstance(parsed)));
}
 
Example #12
Source File: JsonCoercingUtil.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
public static Object parseLiteral(Object input, Map<String, Object> variables) throws CoercingParseLiteralException {
  if (!(input instanceof Value)) {
    log.error("Expected 'Value', got: {}", input);
    throw new CoercingParseLiteralException("Expected 'Value', got: " + input);
  }
  Object result = null;
  if (input instanceof StringValue) {
    result = ((StringValue) input).getValue();
  } else if (input instanceof IntValue) {
    result = ((IntValue) input).getValue();
  } else if (input instanceof FloatValue) {
    result = ((FloatValue) input).getValue();
  } else if (input instanceof BooleanValue) {
    result = ((BooleanValue) input).isValue();
  } else if (input instanceof EnumValue) {
    result = ((EnumValue) input).getName();
  } else if (input instanceof VariableReference) {
    result = variables.get(((VariableReference) input).getName());
  } else if (input instanceof ArrayValue) {
    result = ((ArrayValue) input).getValues().stream()
        .map(v -> parseLiteral(v, variables))
        .collect(toList());
  } else if (input instanceof ObjectValue) {
    result = ((ObjectValue) input).getObjectFields().stream()
        .collect(toMap(ObjectField::getName, f -> parseLiteral(f.getValue(), variables)));
  }
  return result;
}
 
Example #13
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void variableReferenceValue() {
  Value value = VariableReference.newVariableReference().name("a").build();
  Object result = JsonCoercingUtil.parseLiteral(value, Map.of("a", "b"));
  assertThat(result, is("b"));
}
 
Example #14
Source File: GsonScalars.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Object parseLiteral(Object input) {
    return parseJsonValue(((Value) input));
}
 
Example #15
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void enumValue() {
  Value value = EnumValue.newEnumValue("a").build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is("a"));
}
 
Example #16
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void booleanValue() {
  Value value = BooleanValue.newBooleanValue(true).build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is(true));
}
 
Example #17
Source File: JacksonObjectScalars.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Object parseLiteral(Object input, Map<String, Object> variables) {
    return parseJsonValue(((Value) input), variables);
}
 
Example #18
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void floatValue() {
  Value value = FloatValue.newFloatValue(new BigDecimal("1.2")).build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is(new BigDecimal("1.2")));
}
 
Example #19
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Object parseLiteral(Object input, Map<String, Object> variables) {
    return parseObjectValue(((Value) input), variables);
}
 
Example #20
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public static <T extends Value> T literalOrException(Object input, Class<T> valueType) {
    if (valueType.isInstance(input)) {
        return valueType.cast(input);
    }
    throw new CoercingParseLiteralException(errorMessage(input, valueType));
}
 
Example #21
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void intValue() {
  Value value = IntValue.newIntValue(new BigInteger("1")).build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is(new BigInteger("1")));
}
 
Example #22
Source File: STModel.java    From graphql-apigen with Apache License 2.0 4 votes vote down vote up
private String toJavaValue(Value value) {
    // TODO: Implement me!
    return null;
}
 
Example #23
Source File: Scalars.java    From notification with Apache License 2.0 4 votes vote down vote up
public static <T extends Value<?>> T literalOrException(Object input, Class<T> valueType) {
  if (valueType.isInstance(input)) {
    return valueType.cast(input);
  }
  throw new CoercingParseLiteralException(errorMessage(input, valueType));
}
 
Example #24
Source File: JsonCoercingUtilTest.java    From stream-registry with Apache License 2.0 4 votes vote down vote up
@Test
public void stringValue() {
  Value value = StringValue.newStringValue("a").build();
  Object result = JsonCoercingUtil.parseLiteral(value, emptyMap());
  assertThat(result, is("a"));
}
 
Example #25
Source File: ContentTypeBasedDataFetcher.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Adds the required filters to the ES query for the given field
 */
protected void processSelection(String path, Selection currentSelection, BoolQueryBuilder query,
                                List<String> queryFieldIncludes, DataFetchingEnvironment env)  {
    if (currentSelection instanceof Field) {
        // If the current selection is a field
        Field currentField = (Field) currentSelection;

        // Get the original field name
        String propertyName = getOriginalName(currentField.getName());
        // Build the ES-friendly path
        String fullPath = StringUtils.isEmpty(path)? propertyName : path + "." + propertyName;

        // If the field has sub selection
        if (Objects.nonNull(currentField.getSelectionSet())) {
            // If the field is a flattened component
            if (fullPath.matches(COMPONENT_INCLUDE_REGEX)) {
                // Include the 'content-type' field to make sure the type can be resolved during runtime
                String contentTypeFieldPath = fullPath + "." + QUERY_FIELD_NAME_CONTENT_TYPE;
                if (!queryFieldIncludes.contains(contentTypeFieldPath)) {
                    queryFieldIncludes.add(contentTypeFieldPath);
                }
            }

            // Process recursively and finish
            currentField.getSelectionSet().getSelections()
                .forEach(selection -> processSelection(fullPath, selection, query, queryFieldIncludes, env));
            return;
        }

        // Add the field to the list
        logger.debug("Adding selected field '{}' to query", fullPath);
        queryFieldIncludes.add(fullPath);

        // Check the filters to build the ES query
        Optional<Argument> arg =
            currentField.getArguments().stream().filter(a -> a.getName().equals(FILTER_NAME)).findFirst();
        if (arg.isPresent()) {
            logger.debug("Adding filters for field {}", fullPath);
            Value<?> argValue = arg.get().getValue();
            if (argValue instanceof ObjectValue) {
                List<ObjectField> filters = ((ObjectValue) argValue).getObjectFields();
                filters.forEach((filter) -> addFieldFilterFromObjectField(fullPath, filter, query, env));
            } else if (argValue instanceof VariableReference &&
                    env.getVariables().containsKey(((VariableReference) argValue).getName())) {
                Map<String, Object> map =
                        (Map<String, Object>) env.getVariables().get(((VariableReference) argValue).getName());
                map.entrySet().forEach(filter -> addFieldFilterFromMapEntry(fullPath, filter, query, env));
            }
        }
    } else if (currentSelection instanceof InlineFragment) {
        // If the current selection is an inline fragment, process recursively
        InlineFragment fragment = (InlineFragment) currentSelection;
        fragment.getSelectionSet().getSelections()
            .forEach(selection -> processSelection(path, selection, query, queryFieldIncludes, env));
    } else if (currentSelection instanceof FragmentSpread) {
        // If the current selection is a fragment spread, find the fragment and process recursively
        FragmentSpread fragmentSpread = (FragmentSpread) currentSelection;
        FragmentDefinition fragmentDefinition = env.getFragmentsByName().get(fragmentSpread.getName());
        fragmentDefinition.getSelectionSet().getSelections()
            .forEach(selection -> processSelection(path, selection, query, queryFieldIncludes, env));
    }
}