Search in sources :

Example 6 with GraphQLSchemaDefinition

use of org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition in project carbon-apimgt by wso2.

the class PublisherCommonUtils method validateGraphQLSchema.

/**
 * Validate GraphQL Schema.
 *
 * @param filename file name of the schema
 * @param schema   GraphQL schema
 */
public static GraphQLValidationResponseDTO validateGraphQLSchema(String filename, String schema) throws APIManagementException {
    String errorMessage;
    GraphQLValidationResponseDTO validationResponse = new GraphQLValidationResponseDTO();
    boolean isValid = false;
    try {
        if (filename.endsWith(".graphql") || filename.endsWith(".txt") || filename.endsWith(".sdl")) {
            if (schema.isEmpty()) {
                throw new APIManagementException("GraphQL Schema cannot be empty or null to validate it", ExceptionCodes.GRAPHQL_SCHEMA_CANNOT_BE_NULL);
            }
            SchemaParser schemaParser = new SchemaParser();
            TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
            GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry);
            SchemaValidator schemaValidation = new SchemaValidator();
            Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema);
            if (validationErrors.toArray().length > 0) {
                errorMessage = "InValid Schema";
                validationResponse.isValid(Boolean.FALSE);
                validationResponse.errorMessage(errorMessage);
            } else {
                validationResponse.setIsValid(Boolean.TRUE);
                GraphQLValidationResponseGraphQLInfoDTO graphQLInfo = new GraphQLValidationResponseGraphQLInfoDTO();
                GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
                List<URITemplate> operationList = graphql.extractGraphQLOperationList(typeRegistry, null);
                List<APIOperationsDTO> operationArray = APIMappingUtil.fromURITemplateListToOprationList(operationList);
                graphQLInfo.setOperations(operationArray);
                GraphQLSchemaDTO schemaObj = new GraphQLSchemaDTO();
                schemaObj.setSchemaDefinition(schema);
                graphQLInfo.setGraphQLSchema(schemaObj);
                validationResponse.setGraphQLInfo(graphQLInfo);
            }
        } else {
            throw new APIManagementException("Unsupported extension type of file: " + filename, ExceptionCodes.UNSUPPORTED_GRAPHQL_FILE_EXTENSION);
        }
        isValid = validationResponse.isIsValid();
        errorMessage = validationResponse.getErrorMessage();
    } catch (SchemaProblem e) {
        errorMessage = e.getMessage();
    }
    if (!isValid) {
        validationResponse.setIsValid(isValid);
        validationResponse.setErrorMessage(errorMessage);
    }
    return validationResponse;
}
Also used : TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaValidator(graphql.schema.validation.SchemaValidator) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) GraphQLValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseDTO) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) SchemaValidationError(graphql.schema.validation.SchemaValidationError) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GraphQLValidationResponseGraphQLInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLValidationResponseGraphQLInfoDTO) SchemaProblem(graphql.schema.idl.errors.SchemaProblem) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) GraphQLSchemaDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO)

Example 7 with GraphQLSchemaDefinition

use of org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition in project carbon-apimgt by wso2.

the class SynapseArtifactGenerator method generateGatewayArtifact.

@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList) throws APIManagementException {
    RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
    List<String> synapseArtifacts = new ArrayList<>();
    for (APIRuntimeArtifactDto runTimeArtifact : apiRuntimeArtifactDtoList) {
        if (runTimeArtifact.isFile()) {
            String tenantDomain = runTimeArtifact.getTenantDomain();
            String label = runTimeArtifact.getLabel();
            Environment environment = APIUtil.getEnvironments(tenantDomain).get(label);
            GatewayAPIDTO gatewayAPIDTO = null;
            if (environment != null) {
                try (InputStream artifact = (InputStream) runTimeArtifact.getArtifact()) {
                    File baseDirectory = CommonUtil.createTempDirectory(null);
                    try {
                        String extractedFolderPath = ImportUtils.getArchivePathOfExtractedDirectory(baseDirectory.getAbsolutePath(), artifact);
                        if (APIConstants.API_PRODUCT.equals(runTimeArtifact.getType())) {
                            APIProductDTO apiProductDTO = ImportUtils.retrieveAPIProductDto(extractedFolderPath);
                            apiProductDTO.setId(runTimeArtifact.getApiId());
                            APIProduct apiProduct = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, apiProductDTO.getProvider());
                            APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                            apiProduct.setDefinition(apiDefinitionValidationResponse.getContent());
                            gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(apiProduct, environment, tenantDomain, extractedFolderPath);
                        } else {
                            APIDTO apidto = ImportUtils.retrievedAPIDto(extractedFolderPath);
                            API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
                            api.setUUID(apidto.getId());
                            if (APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
                                APIDefinition parser = new OAS3Parser();
                                SwaggerData swaggerData = new SwaggerData(api);
                                String apiDefinition = parser.generateAPIDefinition(swaggerData);
                                api.setSwaggerDefinition(apiDefinition);
                                GraphqlComplexityInfo graphqlComplexityInfo = APIUtil.getComplexityDetails(api);
                                String graphqlSchema = ImportUtils.retrieveValidatedGraphqlSchemaFromArchive(extractedFolderPath);
                                api.setGraphQLSchema(graphqlSchema);
                                GraphQLSchemaDefinition graphQLSchemaDefinition = new GraphQLSchemaDefinition();
                                graphqlSchema = graphQLSchemaDefinition.buildSchemaWithAdditionalInfo(api, graphqlComplexityInfo);
                                api.setGraphQLSchema(graphqlSchema);
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath);
                            } else if (api.getType() != null && (APIConstants.APITransportType.HTTP.toString().equals(api.getType()) || APIConstants.API_TYPE_SOAP.equals(api.getType()) || APIConstants.API_TYPE_SOAPTOREST.equals(api.getType()) || APIConstants.APITransportType.WEBHOOK.toString().equals(api.getType()))) {
                                APIDefinitionValidationResponse apiDefinitionValidationResponse = ImportUtils.retrieveValidatedSwaggerDefinitionFromArchive(extractedFolderPath);
                                api.setSwaggerDefinition(apiDefinitionValidationResponse.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDto(api, environment, tenantDomain, apidto, extractedFolderPath, apiDefinitionValidationResponse);
                            } else if (api.getType() != null && (APIConstants.APITransportType.WS.toString().equals(api.getType()) || APIConstants.APITransportType.SSE.toString().equals(api.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(api.getType()))) {
                                APIDefinitionValidationResponse asyncApiDefinition = ImportUtils.retrieveValidatedAsyncApiDefinitionFromArchive(extractedFolderPath);
                                api.setAsyncApiDefinition(asyncApiDefinition.getContent());
                                gatewayAPIDTO = TemplateBuilderUtil.retrieveGatewayAPIDtoForStreamingAPI(api, environment, tenantDomain, apidto, extractedFolderPath);
                            }
                        }
                        if (gatewayAPIDTO != null) {
                            String content = new Gson().toJson(gatewayAPIDTO);
                            synapseArtifacts.add(content);
                        }
                    } finally {
                        FileUtils.deleteQuietly(baseDirectory);
                    }
                } catch (Exception e) {
                    // only do error since we need to continue for other apis
                    log.error("Error while creating Synapse configurations", e);
                }
            }
        }
    }
    runtimeArtifactDto.setFile(false);
    runtimeArtifactDto.setArtifact(synapseArtifacts);
    return runtimeArtifactDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) InputStream(java.io.InputStream) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) Gson(com.google.gson.Gson) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File)

Example 8 with GraphQLSchemaDefinition

use of org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testGetGraphqlSchemaDefinition.

// 
// @Test
// public void testGetSwagger20Definition() throws Exception {
// int tenantId = -1234;
// Organization org = Mockito.mock(Organization.class);
// PowerMockito.whenNew(Organization.class).withArguments(SAMPLE_TENANT_DOMAIN, null).thenReturn(org);
// 
// AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiPersistenceInstance);
// APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
// identifier.setUuid(SAMPLE_RESOURCE_ID);
// PowerMockito.mockStatic(OASParserUtil.class);
// String swaggerContent = "sample swagger";
// PowerMockito.when(apiPersistenceInstance.getOASDefinition(org ,
// SAMPLE_RESOURCE_ID)).thenReturn(swaggerContent);
// 
// 
// Assert.assertEquals(abstractAPIManager.getOpenAPIDefinition(SAMPLE_RESOURCE_ID, SAMPLE_TENANT_DOMAIN), swaggerContent);
// abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN;
// Assert.assertEquals(abstractAPIManager.getOpenAPIDefinition(identifier), swaggerContent);
// }
@Test
public void testGetGraphqlSchemaDefinition() throws Exception {
    int tenantId = -1234;
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, registryService, tenantManager);
    Mockito.when(tenantManager.getTenantId(SAMPLE_TENANT_DOMAIN)).thenThrow(UserStoreException.class).thenReturn(tenantId);
    APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
    try {
        abstractAPIManager.getGraphqlSchemaDefinition(identifier);
        Assert.fail("Use store exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get graphql schema definition of Graphql API"));
    }
    String schemaContent = "sample graphql schema";
    setFinalStatic(AbstractAPIManager.class.getDeclaredField("schemaDef"), graphQLSchemaDefinition);
    Mockito.when(graphQLSchemaDefinition.getGraphqlSchemaDefinition(identifier, null)).thenReturn(schemaContent);
    Assert.assertEquals(abstractAPIManager.getGraphqlSchemaDefinition(identifier), schemaContent);
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN;
    Assert.assertEquals(abstractAPIManager.getGraphqlSchemaDefinition(identifier), schemaContent);
    Mockito.when(registryService.getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId)).thenThrow(RegistryException.class);
    abstractAPIManager.tenantDomain = null;
    try {
        abstractAPIManager.getGraphqlSchemaDefinition(identifier);
        Assert.fail("Registry exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to get graphql schema definition of Graphql API"));
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 9 with GraphQLSchemaDefinition

use of org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition in project carbon-apimgt by wso2.

the class GraphQLProcessorUtil method getOperationList.

/**
 * This method used to extract operation List.
 *
 * @param operation              operation
 * @param typeDefinitionRegistry TypeDefinitionRegistry
 * @return operationList
 */
public static String getOperationList(OperationDefinition operation, TypeDefinitionRegistry typeDefinitionRegistry) {
    String operationList;
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    ArrayList<String> operationArray = new ArrayList<>();
    List<URITemplate> list = graphql.extractGraphQLOperationList(typeDefinitionRegistry, operation.getOperation().toString());
    ArrayList<String> supportedFields = getSupportedFields(list);
    getNestedLevelOperations(operation.getSelectionSet().getSelections(), supportedFields, operationArray);
    operationList = String.join(",", operationArray);
    return operationList;
}
Also used : ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition)

Example 10 with GraphQLSchemaDefinition

use of org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdGraphqlPoliciesComplexityTypesGet.

@Override
public Response apisApiIdGraphqlPoliciesComplexityTypesGet(String apiId, MessageContext messageContext) throws APIManagementException {
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId, organization);
        API api = apiConsumer.getLightweightAPIByUUID(apiId, organization);
        if (APIConstants.GRAPHQL_API.equals(api.getType())) {
            String schemaContent = apiConsumer.getGraphqlSchema(apiIdentifier);
            List<GraphqlSchemaType> typeList = graphql.extractGraphQLTypeList(schemaContent);
            GraphQLSchemaTypeListDTO graphQLSchemaTypeListDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlSchemaTypeListtoDTO(typeList);
            return Response.ok().entity(graphQLSchemaTypeListDTO).build();
        } else {
            throw new APIManagementException(ExceptionCodes.API_NOT_GRAPHQL);
        }
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving types and fields of API : " + apiId, e, log);
        } else {
            String msg = "Error while retrieving types and fields of the schema of API " + apiId;
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GraphqlSchemaType(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlSchemaType) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Aggregations

GraphQLSchemaDefinition (org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 API (org.wso2.carbon.apimgt.api.model.API)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)3 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 GatewayAPIDTO (org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 GraphqlSchemaType (org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlSchemaType)2 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)2 Gson (com.google.gson.Gson)1 GraphQLSchema (graphql.schema.GraphQLSchema)1 SchemaParser (graphql.schema.idl.SchemaParser)1 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)1 SchemaProblem (graphql.schema.idl.errors.SchemaProblem)1 SchemaValidationError (graphql.schema.validation.SchemaValidationError)1 SchemaValidator (graphql.schema.validation.SchemaValidator)1 File (java.io.File)1