Search in sources :

Example 1 with GraphQLSchemaDefinition

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

the class TemplateBuilderUtil method createAPIGatewayDTOtoPublishAPI.

private static GatewayAPIDTO createAPIGatewayDTOtoPublishAPI(Environment environment, API api, APITemplateBuilder builder, String tenantDomain, String extractedPath, APIDTO apidto, List<ClientCertificateDTO> clientCertificatesDTOList) throws APIManagementException, APITemplateException, XMLStreamException {
    GatewayAPIDTO gatewayAPIDTO = new GatewayAPIDTO();
    gatewayAPIDTO.setName(api.getId().getName());
    gatewayAPIDTO.setVersion(api.getId().getVersion());
    gatewayAPIDTO.setProvider(api.getId().getProviderName());
    gatewayAPIDTO.setApiId(api.getUUID());
    gatewayAPIDTO.setTenantDomain(tenantDomain);
    gatewayAPIDTO.setKeyManagers(api.getKeyManagers());
    String definition;
    boolean isGraphQLSubscriptionAPI = false;
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        // Build schema with additional info
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID() + "_graphQL", gatewayAPIDTO.getLocalEntriesToBeRemove()));
        GatewayContentDTO graphqlLocalEntry = new GatewayContentDTO();
        graphqlLocalEntry.setName(api.getUUID() + "_graphQL");
        graphqlLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "_graphQL" + "\">" + "<![CDATA[" + api.getGraphQLSchema() + "]]>" + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(graphqlLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
        gatewayAPIDTO.setGraphQLSchema(api.getGraphQLSchema());
        Set<URITemplate> uriTemplates = new HashSet<>();
        URITemplate template = new URITemplate();
        template.setAuthType("Any");
        template.setHTTPVerb("POST");
        template.setHttpVerbs("POST");
        template.setUriTemplate("/*");
        uriTemplates.add(template);
        api.setUriTemplates(uriTemplates);
        GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
        if (graphql.isSubscriptionAvailable(api.getGraphQLSchema())) {
            isGraphQLSubscriptionAPI = true;
            // if subscriptions are available add new URI template with wild card resource without http verb.
            template = new URITemplate();
            template.setUriTemplate("/*");
            uriTemplates.add(template);
            api.setUriTemplates(uriTemplates);
            api.setEndpointConfig(populateSubscriptionEndpointConfig(api.getEndpointConfig()));
            addGqlWebSocketTopicMappings(api);
        }
    } 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()))) {
        definition = api.getSwaggerDefinition();
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        GatewayContentDTO apiLocalEntry = new GatewayContentDTO();
        apiLocalEntry.setName(api.getUUID());
        apiLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(apiLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
    } 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()))) {
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(api.getUUID(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        definition = api.getAsyncApiDefinition();
        GatewayContentDTO apiLocalEntry = new GatewayContentDTO();
        apiLocalEntry.setName(api.getUUID());
        apiLocalEntry.setContent("<localEntry key=\"" + api.getUUID() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
        gatewayAPIDTO.setLocalEntriesToBeAdd(addGatewayContentToList(apiLocalEntry, gatewayAPIDTO.getLocalEntriesToBeAdd()));
    }
    if ((APIConstants.GATEWAY_ENV_TYPE_PRODUCTION.equals(environment.getType()) && !APIUtil.isProductionEndpointsExists(api.getEndpointConfig())) || (APIConstants.GATEWAY_ENV_TYPE_SANDBOX.equals(environment.getType()) && !APIUtil.isSandboxEndpointsExists(api.getEndpointConfig()))) {
        if (log.isDebugEnabled()) {
            log.debug("Not adding API to environment " + environment.getName() + " since its endpoint URL " + "cannot be found");
        }
        return null;
    }
    GatewayUtils.setCustomSequencesToBeRemoved(api, gatewayAPIDTO);
    setAPIFaultSequencesToBeAdded(api, gatewayAPIDTO, extractedPath, apidto);
    setCustomSequencesToBeAdded(api, gatewayAPIDTO, extractedPath, apidto);
    setClientCertificatesToBeAdded(tenantDomain, gatewayAPIDTO, clientCertificatesDTOList);
    boolean isWsApi = APIConstants.APITransportType.WS.toString().equals(api.getType());
    if (isWsApi) {
        addWebsocketTopicMappings(api, apidto);
    }
    // Add the API
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        String prototypeScriptAPI = builder.getConfigStringForPrototypeScriptAPI(environment);
        gatewayAPIDTO.setApiDefinition(prototypeScriptAPI);
    } else if (APIConstants.IMPLEMENTATION_TYPE_ENDPOINT.equalsIgnoreCase(api.getImplementation())) {
        String apiConfig = builder.getConfigStringForTemplate(environment);
        gatewayAPIDTO.setApiDefinition(apiConfig);
        org.json.JSONObject endpointConfig = new org.json.JSONObject(api.getEndpointConfig());
        if (!endpointConfig.get(APIConstants.API_ENDPOINT_CONFIG_PROTOCOL_TYPE).equals(APIConstants.ENDPOINT_TYPE_AWSLAMBDA)) {
            if (!isWsApi) {
                addEndpoints(api, builder, gatewayAPIDTO);
            }
            if (isWsApi || isGraphQLSubscriptionAPI) {
                addWebSocketResourceEndpoints(api, builder, gatewayAPIDTO);
            }
        }
    }
    setSecureVaultPropertyToBeAdded(null, api, gatewayAPIDTO);
    return gatewayAPIDTO;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) JSONObject(org.json.simple.JSONObject) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO) HashSet(java.util.HashSet)

Example 2 with GraphQLSchemaDefinition

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

the class ApisApiServiceImpl method getGraphQLPolicyComplexityTypesOfAPI.

/**
 * Get all types and fields of the GraphQL Schema of a given API
 *
 * @param apiId          apiId
 * @param messageContext message context
 * @return Response with all the types and fields found within the schema definition
 */
@Override
public Response getGraphQLPolicyComplexityTypesOfAPI(String apiId, MessageContext messageContext) {
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIIdentifier apiIdentifier;
        if (ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiId) != null) {
            apiIdentifier = APIMappingUtil.getAPIInfoFromUUID(apiId, organization).getId();
        } else {
            apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        }
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        if (APIConstants.GRAPHQL_API.equals(api.getType())) {
            String schemaContent = apiProvider.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) GraphQLSchemaTypeListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLSchemaTypeListDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 3 with GraphQLSchemaDefinition

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

the class AbstractAPIManagerTestCase method init.

@Before
public void init() {
    System.setProperty(CARBON_HOME, "");
    privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.mockStatic(GovernanceUtils.class);
    paginationContext = Mockito.mock(PaginationContext.class);
    PowerMockito.mockStatic(PaginationContext.class);
    PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationContext);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    scopesDAO = Mockito.mock(ScopesDAO.class);
    registry = Mockito.mock(Registry.class);
    genericArtifactManager = Mockito.mock(GenericArtifactManager.class);
    registryService = Mockito.mock(RegistryService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
    keyManager = Mockito.mock(KeyManager.class);
    apiPersistenceInstance = Mockito.mock(APIPersistence.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    KeyManagerDto keyManagerDto = new KeyManagerDto();
    keyManagerDto.setName("default");
    keyManagerDto.setKeyManager(keyManager);
    keyManagerDto.setIssuer("https://localhost");
    Map<String, KeyManagerDto> tenantKeyManagerDtoMap = new HashMap<>();
    tenantKeyManagerDtoMap.put("default", keyManagerDto);
    PowerMockito.when(KeyManagerHolder.getTenantKeyManagers("carbon.super")).thenReturn(tenantKeyManagerDtoMap);
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) HashMap(java.util.HashMap) PaginationContext(org.wso2.carbon.registry.core.pagination.PaginationContext) ScopesDAO(org.wso2.carbon.apimgt.impl.dao.ScopesDAO) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) APIPersistence(org.wso2.carbon.apimgt.persistence.APIPersistence) Before(org.junit.Before)

Example 4 with GraphQLSchemaDefinition

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

the class APIProviderImpl method saveGraphqlSchemaDefinition.

@Override
public void saveGraphqlSchemaDefinition(API api, String schemaDefinition) throws APIManagementException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        GraphQLSchemaDefinition schemaDef = new GraphQLSchemaDefinition();
        schemaDef.saveGraphQLSchemaDefinition(api, schemaDefinition, registry);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition)

Example 5 with GraphQLSchemaDefinition

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

the class APIProviderImplTest method testSaveGraphqlSchemaDefinition.

@Test
public void testSaveGraphqlSchemaDefinition() throws Exception {
    Resource resource = new ResourceImpl();
    String resourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + "admin" + RegistryConstants.PATH_SEPARATOR + "API1" + RegistryConstants.PATH_SEPARATOR + "1.0.0" + RegistryConstants.PATH_SEPARATOR;
    String schemaContent = "sample schema";
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(apiId);
    Mockito.when(APIUtil.getGraphqlDefinitionFilePath("API1", "1.0.0", "admin")).thenReturn(resourcePath);
    Resource resourceMock = Mockito.mock(Resource.class);
    resourceMock.setContent(schemaContent);
    resourceMock.setMediaType(String.valueOf(ContentType.TEXT_PLAIN));
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    Mockito.when(userRegistry.newResource()).thenReturn(resource);
    PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
    PowerMockito.doNothing().when(APIUtil.class, "setResourcePermissions", Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
    GraphQLSchemaDefinition graphQLSchemaDefinition = Mockito.mock(GraphQLSchemaDefinition.class);
    PowerMockito.doCallRealMethod().when(graphQLSchemaDefinition).saveGraphQLSchemaDefinition(api, schemaContent, userRegistry);
    // org.wso2.carbon.registry.api.RegistryException
    Mockito.doThrow(RegistryException.class).when(registry).put(Matchers.anyString(), any(Resource.class));
    try {
        graphQLSchemaDefinition.saveGraphQLSchemaDefinition(api, schemaContent, registry);
    } catch (APIManagementException e) {
        String msg = "Error while adding Graphql Definition for API1-1.0.0";
        Assert.assertEquals(msg, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) GraphQLSchemaDefinition(org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

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