Search in sources :

Example 21 with SchemaParser

use of graphql.schema.idl.SchemaParser in project carbon-apimgt by wso2.

the class GraphQLRequestProcessorTest method testHandleRequestSuccess.

@Test
public void testHandleRequestSuccess() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    int msgSize = 100;
    String msgText = "{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{}," + "\"operationName\":null,\"query\":\"subscription {\\n  " + "liftStatusChange {\\n    id\\n    name\\n    }\\n}\\n\"}}";
    PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
    // Get schema and parse
    String graphqlDirPath = "graphQL" + File.separator;
    String relativePath = graphqlDirPath + "schema_with_additional_props.graphql";
    String schemaString = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry registry = schemaParser.parse(schemaString);
    GraphQLSchema schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
    GraphQLSchemaDTO schemaDTO = new GraphQLSchemaDTO(schema, registry);
    inboundMessageContext.setGraphQLSchemaDTO(schemaDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(responseDTO);
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setHttpVerb("SUBSCRIPTION");
    verbInfoDTO.setThrottling("Unlimited");
    PowerMockito.when(InboundWebsocketProcessorUtil.findMatchingVerb("liftStatusChange", inboundMessageContext)).thenReturn(verbInfoDTO);
    APIKeyValidationInfoDTO infoDTO = new APIKeyValidationInfoDTO();
    infoDTO.setGraphQLMaxComplexity(4);
    infoDTO.setGraphQLMaxDepth(3);
    inboundMessageContext.setInfoDTO(infoDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize, verbInfoDTO, inboundMessageContext, "1")).thenReturn(responseDTO);
    GraphQLRequestProcessor graphQLRequestProcessor = new GraphQLRequestProcessor();
    InboundProcessorResponseDTO processorResponseDTO = graphQLRequestProcessor.handleRequest(msgSize, msgText, inboundMessageContext);
    Assert.assertFalse(processorResponseDTO.isError());
    Assert.assertNull(processorResponseDTO.getErrorMessage());
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getOperation(), "liftStatusChange");
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getVerbInfoDTO().getHttpVerb(), "SUBSCRIPTION");
    Assert.assertEquals(inboundMessageContext.getVerbInfoForGraphQLMsgId("1").getVerbInfoDTO().getThrottling(), "Unlimited");
}
Also used : VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) GraphQLSchemaDTO(org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 22 with SchemaParser

use of graphql.schema.idl.SchemaParser in project carbon-apimgt by wso2.

the class GraphQLSchemaDefinition method extractGraphQLTypeList.

/**
 * 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;
}
Also used : ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) FieldDefinition(graphql.language.FieldDefinition) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaParser(graphql.schema.idl.SchemaParser) OperationTypeDefinition(graphql.language.OperationTypeDefinition) ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) TypeDefinition(graphql.language.TypeDefinition) GraphqlSchemaType(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlSchemaType)

Example 23 with SchemaParser

use of graphql.schema.idl.SchemaParser in project carbon-apimgt by wso2.

the class GraphQLAPIHandlerTest method setup.

@Before
public void setup() throws IOException {
    messageContext = Mockito.mock(Axis2MessageContext.class);
    axis2MessageContext = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    omElement = Mockito.mock(OMElement.class);
    dataHolder = Mockito.mock(DataHolder.class);
    SOAPEnvelope soapEnvelope = Mockito.mock(SOAPEnvelope.class);
    SOAPBody soapBody = Mockito.mock(SOAPBody.class);
    PowerMockito.mockStatic(DataHolder.class);
    OMElement body = Mockito.mock(OMElement.class);
    Map propertyList = Mockito.mock(Map.class);
    Mockito.when(messageContext.getAxis2MessageContext()).thenReturn(axis2MessageContext);
    Mockito.when(axis2MessageContext.getIncomingTransportName()).thenReturn("ws");
    Mockito.when(messageContext.getProperty(APIConstants.GRAPHQL_SUBSCRIPTION_REQUEST)).thenReturn(true);
    Mockito.when(axis2MessageContext.getIncomingTransportName()).thenReturn("wss");
    Mockito.when(axis2MessageContext.getEnvelope()).thenReturn(soapEnvelope);
    Mockito.when(soapEnvelope.getBody()).thenReturn(soapBody);
    Mockito.when(soapBody.getFirstElement()).thenReturn(body);
    Mockito.when(body.getFirstChildWithName(QName.valueOf("query"))).thenReturn(omElement);
    Mockito.when(messageContext.getProperties()).thenReturn(propertyList);
    Mockito.when(messageContext.getProperty(REST_SUB_REQUEST_PATH)).thenReturn("/");
    Mockito.when(propertyList.get(REST_SUB_REQUEST_PATH)).thenReturn("/");
    Mockito.when(propertyList.get(REST_SUB_REQUEST_PATH).toString().split("/?query=")).thenReturn(new String[0]);
    Mockito.when(DataHolder.getInstance()).thenReturn(dataHolder);
    // Get schema and parse
    schemaDTOMap = new HashMap<>();
    String graphqlDirPath = "graphQL" + File.separator;
    String relativePath = graphqlDirPath + "schema_with_additional_props.graphql";
    String schemaString = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry registry = schemaParser.parse(schemaString);
    GraphQLSchema schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
    GraphQLSchemaDTO schemaDTO = new GraphQLSchemaDTO(schema, registry);
    schemaDTOMap.put("12345", schemaDTO);
    Mockito.when(dataHolder.getApiToGraphQLSchemaDTOMap()).thenReturn(schemaDTOMap);
}
Also used : TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) OMElement(org.apache.axiom.om.OMElement) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) SOAPBody(org.apache.axiom.soap.SOAPBody) DataHolder(org.wso2.carbon.apimgt.gateway.internal.DataHolder) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) GraphQLSchemaDTO(org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO) HashMap(java.util.HashMap) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Before(org.junit.Before)

Example 24 with SchemaParser

use of graphql.schema.idl.SchemaParser in project carbon-apimgt by wso2.

the class GraphqlQueryAnalysisMappingUtil method fromDTOtoValidatedGraphqlComplexityInfo.

/**
 * Converts a GraphQLQueryComplexityInfo DTO object into a GraphqlComplexityInfo object. During this process a
 * basic validation is done comparing with the types of the schema
 *
 * @param graphQLQueryComplexityInfoDTO GraphQLQueryComplexityInfoDTO object
 * @param schema                        GraphQL Schema
 * @return a new GraphqlComplexityInfo object corresponding to given GraphQLQueryComplexityInfoDTO object
 */
public static GraphqlComplexityInfo fromDTOtoValidatedGraphqlComplexityInfo(GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO, String schema) {
    SchemaParser schemaParser = new SchemaParser();
    Set<String> complexityInfoTypeSet = schemaParser.parse(schema).types().keySet();
    GraphqlComplexityInfo graphqlComplexityInfo = new GraphqlComplexityInfo();
    List<CustomComplexityDetails> customComplexityDetailsList = new ArrayList<CustomComplexityDetails>();
    for (GraphQLCustomComplexityInfoDTO graphQLCustomComplexityInfoDTO : graphQLQueryComplexityInfoDTO.getList()) {
        String complexityType = graphQLCustomComplexityInfoDTO.getType();
        if (complexityInfoTypeSet.contains(complexityType)) {
            CustomComplexityDetails customComplexityDetails = new CustomComplexityDetails();
            customComplexityDetails.setType(complexityType);
            customComplexityDetails.setField(graphQLCustomComplexityInfoDTO.getField());
            customComplexityDetails.setComplexityValue(graphQLCustomComplexityInfoDTO.getComplexityValue());
            customComplexityDetailsList.add(customComplexityDetails);
        } else {
            log.error("Complexity Type : " + complexityType + " is not included in the original schema. Hence " + "skipped.");
        }
    }
    graphqlComplexityInfo.setList(customComplexityDetailsList);
    return graphqlComplexityInfo;
}
Also used : GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) ArrayList(java.util.ArrayList) GraphQLCustomComplexityInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLCustomComplexityInfoDTO) SchemaParser(graphql.schema.idl.SchemaParser) CustomComplexityDetails(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.CustomComplexityDetails)

Example 25 with SchemaParser

use of graphql.schema.idl.SchemaParser in project graphql-java by graphql-java.

the class HttpMain method buildStarWarsSchema.

private GraphQLSchema buildStarWarsSchema() {
    // 
    if (starWarsSchema == null) {
        // 
        // 
        // the fetcher of friends uses java-dataloader to make the circular friends fetching
        // more efficient by batching and caching the calls to load Character friends
        // 
        DataFetcher friendsFetcher = environment -> {
            DataLoaderRegistry dataloaderRegistry = asMapGet(environment.getContext(), "dataloaderRegistry");
            DataLoader friendsDataLoader = dataloaderRegistry.getDataLoader("friends");
            List<String> friendIds = asMapGet(environment.getSource(), "friends");
            return friendsDataLoader.loadMany(friendIds);
        };
        // 
        // reads a file that provides the schema types
        // 
        Reader streamReader = loadSchemaFile("starWarsSchemaAnnotated.graphqls");
        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(streamReader);
        // 
        // the runtime wiring is used to provide the code that backs the
        // logical schema
        // 
        TypeResolver characterTypeResolver = env -> {
            Map<String, Object> obj = (Map<String, Object>) env.getObject();
            String id = (String) obj.get("id");
            GraphQLSchema schema = env.getSchema();
            if (StarWarsData.isHuman(id)) {
                return (GraphQLObjectType) schema.getType("Human");
            } else {
                return (GraphQLObjectType) schema.getType("Droid");
            }
        };
        RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring().type(newTypeWiring("Query").dataFetcher("hero", StarWarsData.getHeroDataFetcher()).dataFetcher("human", StarWarsData.getHumanDataFetcher()).dataFetcher("droid", StarWarsData.getDroidDataFetcher())).type(newTypeWiring("Human").dataFetcher("friends", friendsFetcher)).type(newTypeWiring("Droid").dataFetcher("friends", friendsFetcher)).type(newTypeWiring("Character").typeResolver(characterTypeResolver)).type(newTypeWiring("Episode").enumValues(StarWarsData.getEpisodeResolver())).build();
        // finally combine the logical schema with the physical runtime
        starWarsSchema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
    }
    return starWarsSchema;
}
Also used : Request(org.eclipse.jetty.server.Request) ExecutionInput.newExecutionInput(graphql.ExecutionInput.newExecutionInput) DataLoaderRegistry(org.dataloader.DataLoaderRegistry) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) GraphQL(graphql.GraphQL) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) ExecutionResult(graphql.ExecutionResult) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) HttpServletRequest(javax.servlet.http.HttpServletRequest) BatchLoader(org.dataloader.BatchLoader) DataLoaderDispatcherInstrumentationOptions.newOptions(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentationOptions.newOptions) SchemaParser(graphql.schema.idl.SchemaParser) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) DataFetcher(graphql.schema.DataFetcher) GraphQLSchema(graphql.schema.GraphQLSchema) TracingInstrumentation(graphql.execution.instrumentation.tracing.TracingInstrumentation) TypeResolver(graphql.schema.TypeResolver) Server(org.eclipse.jetty.server.Server) StarWarsData(graphql.StarWarsData) GraphQLObjectType(graphql.schema.GraphQLObjectType) HandlerList(org.eclipse.jetty.server.handler.HandlerList) HttpServletResponse(javax.servlet.http.HttpServletResponse) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) IOException(java.io.IOException) DataLoader(org.dataloader.DataLoader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) TypeRuntimeWiring.newTypeWiring(graphql.schema.idl.TypeRuntimeWiring.newTypeWiring) ExecutionInput(graphql.ExecutionInput) ChainedInstrumentation(graphql.execution.instrumentation.ChainedInstrumentation) List(java.util.List) Instrumentation(graphql.execution.instrumentation.Instrumentation) RuntimeWiring(graphql.schema.idl.RuntimeWiring) SchemaGenerator(graphql.schema.idl.SchemaGenerator) InputStream(java.io.InputStream) TypeResolver(graphql.schema.TypeResolver) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaGenerator(graphql.schema.idl.SchemaGenerator) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) DataLoader(org.dataloader.DataLoader) RuntimeWiring(graphql.schema.idl.RuntimeWiring) DataLoaderRegistry(org.dataloader.DataLoaderRegistry) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) HandlerList(org.eclipse.jetty.server.handler.HandlerList) List(java.util.List) DataFetcher(graphql.schema.DataFetcher) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

SchemaParser (graphql.schema.idl.SchemaParser)36 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)35 GraphQLSchema (graphql.schema.GraphQLSchema)27 SchemaGenerator (graphql.schema.idl.SchemaGenerator)21 RuntimeWiring (graphql.schema.idl.RuntimeWiring)20 GraphQL (graphql.GraphQL)16 RuntimeWiring.newRuntimeWiring (graphql.schema.idl.RuntimeWiring.newRuntimeWiring)14 Test (org.junit.Test)14 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)11 GraphQLSchemaDTO (org.wso2.carbon.apimgt.api.gateway.GraphQLSchemaDTO)8 HashMap (java.util.HashMap)7 Map (java.util.Map)7 GET (io.vertx.core.http.HttpMethod.GET)6 ArrayList (java.util.ArrayList)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 InboundMessageContext (org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext)6 InboundProcessorResponseDTO (org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO)6 AbstractVerticle (io.vertx.core.AbstractVerticle)5 Router (io.vertx.ext.web.Router)5 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)5