graphql.validation.ValidationError Java Examples

The following examples show how to use graphql.validation.ValidationError. 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: TransformException.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Override
public DataFetcherResult.Builder<Object> appendDataFetcherResult(DataFetcherResult.Builder<Object> builder,
        DataFetchingEnvironment dfe) {
    DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters
            .newExceptionParameters()
            .dataFetchingEnvironment(dfe)
            .exception(super.getCause())
            .build();

    SourceLocation sourceLocation = getSourceLocation(dfe, handlerParameters);

    List<String> paths = toPathList(handlerParameters.getPath());

    ValidationError error = new ValidationError(ValidationErrorType.WrongType,
            sourceLocation, "argument '" + field.getName() + "' with value 'StringValue{value='" + parameterValue
                    + "'}' is not a valid '" + getScalarTypeName() + "'",
            paths);

    return builder.error(error);
}
 
Example #2
Source File: ExecutionErrorsServiceTest.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Test
void testToJsonErrors_WhenExceptionWhileValidationErrorCaught_ShouldReturnJsonBodyWithCustomExtensions() {
    // Given
    Map<String, Object> extensions = new HashMap<>();
    extensions.put("code", "OPERATION_FAILED");
    ValidationError validationError = ValidationError.newValidationError()
            .validationErrorType(ValidationErrorType.UnknownDirective)
            .description("TestDescription")
            .queryPath(singletonList("Test-Path"))
            .extensions(extensions)
            .build();

    // When
    JsonArray jsonArray = executionErrorsService.toJsonErrors(singletonList(validationError));

    // Then
    JsonObject extensionJsonObject = jsonArray.getJsonObject(0).getJsonObject("extensions");
    assertThat(extensionJsonObject.getString("description")).isEqualTo("TestDescription");
    assertThat(extensionJsonObject.getString("validationErrorType")).isEqualTo("UnknownDirective");
    assertThat(extensionJsonObject.getJsonArray("queryPath").getString(0)).isEqualTo("Test-Path");
    assertThat(extensionJsonObject.getString("classification")).isEqualTo("ValidationError");
    assertThat(extensionJsonObject.getString("code")).isEqualTo("OPERATION_FAILED");
}
 
Example #3
Source File: ExecutionErrorsService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Optional<JsonObject> getOptionalExtensions(GraphQLError error) {
    if (error instanceof ValidationError) {
        return getValidationExtensions((ValidationError) error);
    } else if (error instanceof ExceptionWhileDataFetching) {
        return getDataFetchingExtensions((ExceptionWhileDataFetching) error);
    }
    return Optional.empty();
}
 
Example #4
Source File: ExecutionErrorsService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Optional<JsonObject> getValidationExtensions(ValidationError error) {
    JsonObjectBuilder objectBuilder = jsonBuilderFactory.createObjectBuilder();

    addKeyValue(objectBuilder, DESCRIPTION, error.getDescription());
    addKeyValue(objectBuilder, VALIDATION_ERROR_TYPE, error.getValidationErrorType().toString());
    objectBuilder.add(QUERYPATH, toJsonArray(error.getQueryPath()));
    addKeyValue(objectBuilder, CLASSIFICATION, error.getErrorType().toString());
    Map<String, Object> extensions = error.getExtensions();
    populateCustomExtensions(objectBuilder, extensions);
    return Optional.of(objectBuilder.build());
}
 
Example #5
Source File: QueryCache.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public InstrumentationContext<List<ValidationError>> beginValidation(
        InstrumentationValidationParameters parameters) {

    ExecutionFunction executionFunction = executionFunctionTL.get();
    executionFunctionTL.remove();
    if (executionFunction != null) {
        return new ValidationInstrumentationContext(executionFunction);
    }
    return super.beginValidation(parameters);
}
 
Example #6
Source File: QueryCache.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompleted(List<ValidationError> validationErrors, Throwable t) {
    // at this point, we know the validation is complete - go ahead and add it to the cache if no errors
    if (t == null && (validationErrors == null || validationErrors.isEmpty())) {
        // valid, uncached query - add to cache
        cache.computeIfAbsent(executionFunction.getQuery(), executionFunction);
        log.addedToCache(executionFunction.getQuery());
    }
}
 
Example #7
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method validate the payload
 *
 * @param messageContext message context of the request
 * @param document       graphQL schema of the request
 * @return true or false
 */
private boolean validatePayloadWithSchema(MessageContext messageContext, Document document) {
    ArrayList<String> validationErrorMessageList = new ArrayList<>();
    List<ValidationError> validationErrors;
    String validationErrorMessage;

    synchronized (apiUUID + CLASS_NAME_AND_METHOD) {
        if (schema == null) {
            Entry localEntryObj = (Entry) messageContext.getConfiguration().getLocalRegistry().get(apiUUID +
                    GRAPHQL_IDENTIFIER);
            if (localEntryObj != null) {
                SchemaParser schemaParser = new SchemaParser();
                schemaDefinition = localEntryObj.getValue().toString();
                TypeDefinitionRegistry registry = schemaParser.parse(schemaDefinition);
                schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
            }
        }
    }

    validationErrors = validator.validateDocument(schema, document);
    if (validationErrors != null && validationErrors.size() > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Validation failed for " + document);
        }
        for (ValidationError error : validationErrors) {
            validationErrorMessageList.add(error.getDescription());
        }
        validationErrorMessage = String.join(",", validationErrorMessageList);
        handleFailure(messageContext, validationErrorMessage);
        return false;
    }
    return true;
}
 
Example #8
Source File: QueryCache.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public void onDispatched(CompletableFuture<List<ValidationError>> result) {
    // no-op
}
 
Example #9
Source File: ValidatedQuery.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
public List<ValidationError> getErrors() {
    return errors;
}
 
Example #10
Source File: ValidatedQuery.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
public List<ValidationError> getErrors() {
    return errors;
}
 
Example #11
Source File: QueryValidator.java    From hypergraphql with Apache License 2.0 3 votes vote down vote up
public ValidatedQuery validateQuery(String query) {

        ValidatedQuery result = new ValidatedQuery();
        result.errors = validationErrors;

        Document document;

        try {

            document = parser.parseDocument(query);
            result.parsedQuery = document;

        } catch (Exception e) {
            ValidationError err = new ValidationError(ValidationErrorType.InvalidSyntax, new SourceLocation(0, 0), "Invalid query syntax.");
            validationErrors.add(err);
            result.valid = false;

            return result;
        }

        validationErrors.addAll(validator.validateDocument(schema, document));
        if (validationErrors.size() > 0) {
            result.valid = false;

            return result;

        }

        result.valid = true;

        return result;

    }
 
Example #12
Source File: QueryValidator.java    From hypergraphql with Apache License 2.0 3 votes vote down vote up
public ValidatedQuery validateQuery(String query) {

        ValidatedQuery result = new ValidatedQuery();
        result.errors = validationErrors;

        Document document;

        try {

            document = parser.parseDocument(query);
            result.parsedQuery = document;

        } catch (Exception e) {
            ValidationError err = new ValidationError(ValidationErrorType.InvalidSyntax, new SourceLocation(0, 0), "Invalid query syntax.");
            validationErrors.add(err);
            result.valid = false;

            return result;
        }

        validationErrors.addAll(validator.validateDocument(schema, document));
        if (validationErrors.size() > 0) {
            result.valid = false;

            return result;

        }

        result.valid = true;

        return result;

    }