use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPIGraphQLSchema.
/**
* Get GraphQL Schema of given API
*
* @param apiId apiId
* @param accept
* @param ifNoneMatch If--Match header value
* @param messageContext message context
* @return Response with GraphQL Schema
*/
@Override
public Response getAPIGraphQLSchema(String apiId, String accept, String ifNoneMatch, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// this will fail if user does not have access to the API or the API does not exist
APIIdentifier apiIdentifier;
if (ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId) != null) {
apiIdentifier = APIMappingUtil.getAPIInfoFromUUID(apiId, organization).getId();
} else {
apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
}
String schemaContent = apiProvider.getGraphqlSchema(apiIdentifier);
GraphQLSchemaDTO dto = new GraphQLSchemaDTO();
dto.setSchemaDefinition(schemaContent);
dto.setName(apiIdentifier.getProviderName() + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR + apiIdentifier.getApiName() + apiIdentifier.getVersion() + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION);
return Response.ok().entity(dto).build();
} 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 schema of API: " + apiId, e, log);
} else {
String errorMessage = "Error while retrieving schema of API: " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO 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.rest.api.publisher.v1.dto.GraphQLSchemaDTO in project carbon-apimgt by wso2.
the class GraphQLRequestProcessorTest method testHandleRequestScopeValidationSkipWhenSecurityDisabled.
@Test
public void testHandleRequestScopeValidationSkipWhenSecurityDisabled() 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);
// VerbInfoDTO with security disabled
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb("SUBSCRIPTION");
verbInfoDTO.setThrottling("Unlimited");
verbInfoDTO.setAuthType("None");
PowerMockito.when(InboundWebsocketProcessorUtil.findMatchingVerb("liftStatusChange", inboundMessageContext)).thenReturn(verbInfoDTO);
// Creating response for scope validation
GraphQLProcessorResponseDTO graphQLProcessorResponseDTO = new GraphQLProcessorResponseDTO();
graphQLProcessorResponseDTO.setError(true);
graphQLProcessorResponseDTO.setErrorCode(WebSocketApiConstants.FrameErrorConstants.RESOURCE_FORBIDDEN_ERROR);
graphQLProcessorResponseDTO.setErrorMessage("User is NOT authorized to access the Resource");
graphQLProcessorResponseDTO.setCloseConnection(false);
graphQLProcessorResponseDTO.setId("1");
PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(inboundMessageContext, "liftStatusChange", "1")).thenReturn(graphQLProcessorResponseDTO);
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.assertNotEquals(processorResponseDTO.getErrorMessage(), "User is NOT authorized to access the Resource");
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO 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");
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaDTO 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);
}
Aggregations