Java Code Examples for graphql.schema.idl.SchemaParser#parse()

The following examples show how to use graphql.schema.idl.SchemaParser#parse() . 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: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Operations from given schema
 * @param schema graphQL Schema
 * @return the arrayList of APIOperationsDTOextractGraphQLOperationList
 *
 */
public List<URITemplate> extractGraphQLOperationList(String schema, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) ||
                entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION)
                || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
            if (type == null) {
                addOperations(entry, operationArray);
            } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                addOperations(entry, operationArray);
            }
        }
    }
    return operationArray;
}
 
Example 2
Source File: ApolloTestsServer.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private GraphQL setupWsGraphQL() {
  String schema = vertx.fileSystem().readFileBlocking("counter.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("staticCounter", this::staticCounter))
    .type("Subscription", builder -> builder.dataFetcher("counter", this::counter))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example 3
Source File: VertxBatchLoaderTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .type("Link", builder -> builder.dataFetcher("postedBy", this::getLinkPostedBy))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
  DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation();

  return GraphQL.newGraphQL(graphQLSchema)
    .instrumentation(dispatcherInstrumentation)
    .build();
}
 
Example 4
Source File: VertxDataFetcherTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> {
      VertxDataFetcher<Object> dataFetcher = VertxDataFetcher.create((env, fut) -> fut.complete(getAllLinks(env)));
      return builder.dataFetcher("allLinks", dataFetcher);
    })
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example 5
Source File: VertxMappedBatchLoaderTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .type("Link", builder -> builder.dataFetcher("postedBy", this::getLinkPostedBy))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
  DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation();

  return GraphQL.newGraphQL(graphQLSchema)
    .instrumentation(dispatcherInstrumentation)
    .build();
}
 
Example 6
Source File: GraphQLTestBase.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example 7
Source File: LocaleTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("locale.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("locale", this::getLocale))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example 8
Source File: ApolloWSHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("counter.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("staticCounter", this::getStaticCounter))
    .type("Subscription", builder -> builder.dataFetcher("counter", this::getCounter))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example 9
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Types and Fields from given schema
 *
 * @param schema GraphQL Schema
 * @return list of all types and fields
 */
public List<GraphqlSchemaType> extractGraphQLTypeList(String schema) {
    List<GraphqlSchemaType> typeList = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> list = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : list.entrySet()) {
        if (entry.getValue() instanceof ObjectTypeDefinition) {
            GraphqlSchemaType graphqlSchemaType = new GraphqlSchemaType();
            List<String> fieldList = new ArrayList<>();
            graphqlSchemaType.setType(entry.getValue().getName());
            for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
                fieldList.add(fieldDef.getName());
            }
            graphqlSchemaType.setFieldList(fieldList);
            typeList.add(graphqlSchemaType);
        }
    }
    return typeList;
}
 
Example 10
Source File: ApiDesignResourceInfo.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
private static ApiDesignResourceInfo fromGraphQLContent(String content) {
    try {
        SchemaParser schemaParser = new SchemaParser();
        TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(content);
        int numTypes = typeDefinitionRegistry.types().size();
        ApiDesignResourceInfo info = new ApiDesignResourceInfo();
        info.setFormat(FormatType.SDL);
        info.setName("Imported GraphQL Schema");
        String typeList = String.join(", ", typeDefinitionRegistry.types().keySet());
        info.setDescription("An imported GraphQL schema with the following " + numTypes + " types: " + typeList);
        info.setType(ApiDesignType.GraphQL);
        return info;
    } catch (Exception e) {
    }
    return null;
}
 
Example 11
Source File: HGQLConfig.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private HGQLConfig(final InputStream inputStream) {

        ObjectMapper mapper = new ObjectMapper();

        try {
            HGQLConfig config = mapper.readValue(inputStream, HGQLConfig.class);

            SchemaParser schemaParser = new SchemaParser();
            TypeDefinitionRegistry registry = schemaParser.parse(new File(config.schemaFile));

            this.name = config.name;
            this.schemaFile = config.schemaFile;
            this.graphqlConfig = config.graphqlConfig;
            checkServicePorts(config.serviceConfigs);
            this.serviceConfigs = config.serviceConfigs;
            HGQLSchemaWiring wiring = new HGQLSchemaWiring(registry, name, serviceConfigs);
            this.schema = wiring.getSchema();
            this.hgqlSchema = wiring.getHgqlSchema();
        } catch (IOException e) {
            throw new HGQLConfigurationException("Error reading from configuration file", e);
        }
    }
 
Example 12
Source File: GraphQLIntegrationTest.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
private static GraphQLSchema getGraphQLSchema() throws Exception {
  SchemaParser schemaParser = new SchemaParser();
  SchemaGenerator schemaGenerator = new SchemaGenerator();

  URL resource = Thread.currentThread().getContextClassLoader().getResource("schema.graphqls");
  Path path = Paths.get(resource.toURI());
  String s = read(path);

  TypeDefinitionRegistry registry = schemaParser.parse(s);

  RuntimeWiring wiring =
      RuntimeWiring.newRuntimeWiring()
          .type(
              newTypeWiring("Query")
                  .dataFetcher("bookById", GraphQLDataFetchers.getBookByIdDataFetcher()))
          .type(
              newTypeWiring("Book")
                  .dataFetcher("author", GraphQLDataFetchers.getAuthorDataFetcher()))
          .build();

  return schemaGenerator.makeExecutableSchema(registry, wiring);
}
 
Example 13
Source File: VertxGraphqlResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void setupRouter(@Observes Router router) {
    String schema = "type Query{hello: String}";

    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
            .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

    router.route("/graphql").handler(ApolloWSHandler.create(graphQL));
    router.route("/graphql").handler(GraphQLHandler.create(graphQL));
}
 
Example 14
Source File: HGQLConfigService.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
HGQLConfig loadHGQLConfig(final String hgqlConfigPath, final InputStream inputStream, final String username, final String password, boolean classpath) {

        final ObjectMapper mapper = new ObjectMapper();

        try {

            final HGQLConfig config = mapper.readValue(inputStream, HGQLConfig.class);
            final SchemaParser schemaParser = new SchemaParser();

            final String fullSchemaPath = extractFullSchemaPath(hgqlConfigPath, config.getSchemaFile());

            LOGGER.debug("Schema config path: " + fullSchemaPath);

            final Reader reader = selectAppropriateReader(fullSchemaPath, username, password, classpath);
            final TypeDefinitionRegistry registry =
                    schemaParser.parse(reader);

            final HGQLSchemaWiring wiring = new HGQLSchemaWiring(registry, config.getName(), config.getServiceConfigs());
            config.setGraphQLSchema(wiring.getSchema());
            config.setHgqlSchema(wiring.getHgqlSchema());
            return config;

        } catch (IOException | URISyntaxException e) {
            throw new HGQLConfigurationException("Error reading from configuration file", e);
        }
    }
 
Example 15
Source File: GraphQLResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public void setupRouter(@Observes Router router) {
    SchemaParser schemaParser = new SchemaParser();
    final TypeDefinitionRegistry typeDefinitionRegistry;
    try (Reader r = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("graphql/schema.graphql"),
            StandardCharsets.UTF_8)) {
        typeDefinitionRegistry = schemaParser.parse(r);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    DataFetcher<CompletionStage<Book>> dataFetcher = environment -> {
        CompletableFuture<Book> completableFuture = new CompletableFuture<>();
        Book book = getBookById(environment);
        completableFuture.complete(book);
        return completableFuture;
    };

    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder -> builder.dataFetcher("bookById", dataFetcher))
            .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

    router.route("/graphql/server").handler(GraphQLHandler.create(graphQL));
}
 
Example 16
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 17
Source File: BarleyGraphQLSchema.java    From barleydb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BarleyGraphQLSchema(SpecRegistry specRegistry, Environment env, String namespace, CustomQueries customQueries) {
	this.specRegistry = specRegistry;
	this.env = env;
	this.namespace = namespace;
	this.queryCustomizations = new GraphQLQueryCustomizations();
	this.queryCustomizations.setShouldBreakPredicate(new DefaultQueryBreaker(env, namespace, 3, 4));

       GenerateGrapqlSDL graphSdl = new GenerateGrapqlSDL(specRegistry, customQueries);
       
       SchemaParser schemaParser = new SchemaParser();
       sdlString = graphSdl.createSdl();
       LOG.info(sdlString);
       System.out.println(sdlString);
       
       TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(sdlString);
       RuntimeWiring.Builder wiringBuilder = newRuntimeWiring()
               .type("Query", builder -> builder.defaultDataFetcher(new QueryDataFetcher(env, namespace, customQueries)));
       
       specRegistry.getDefinitions().stream()
       .map(DefinitionsSpec::getEntitySpecs)
       .flatMap(Collection::stream)
       .forEach(eSpec -> wiringBuilder.type(getSimpleName(eSpec.getClassName()), builder ->  builder.defaultDataFetcher(new EntityDataFetcher(env, namespace))));
       
        RuntimeWiring runtimeWiring = wiringBuilder.build();        
       
       SchemaGenerator schemaGenerator = new SchemaGenerator();
       this.graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
}