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;
}
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;
}
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"));
}
}
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;
}
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;
}
Aggregations