use of org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo in project carbon-apimgt by wso2.
the class ExportUtils method addAPIMetaInformationToArchive.
/**
* Retrieve meta information of the API to export and store those in the archive directory.
* URL template information are stored in swagger.json definition while rest of the required
* data are in api.json
*
* @param archivePath Folder path to export meta information to export
* @param apiDtoToReturn API DTO to be exported
* @param exportFormat Export format of file
* @param apiProvider API Provider
* @param apiIdentifier API Identifier
* @param organization Organization Identifier
* @throws APIImportExportException If an error occurs while exporting meta information
*/
public static void addAPIMetaInformationToArchive(String archivePath, APIDTO apiDtoToReturn, ExportFormat exportFormat, APIProvider apiProvider, APIIdentifier apiIdentifier, String organization) throws APIImportExportException {
CommonUtil.createDirectory(archivePath + File.separator + ImportExportConstants.DEFINITIONS_DIRECTORY);
try {
// If a streaming API is exported, it does not contain a swagger file.
// Therefore swagger export is only required for REST or SOAP based APIs
String apiType = apiDtoToReturn.getType().toString();
API api = APIMappingUtil.fromDTOtoAPI(apiDtoToReturn, apiDtoToReturn.getProvider());
api.setOrganization(organization);
api.setId(apiIdentifier);
if (!PublisherCommonUtils.isStreamingAPI(apiDtoToReturn)) {
// For Graphql APIs, the graphql schema definition should be exported.
if (StringUtils.equals(apiType, APIConstants.APITransportType.GRAPHQL.toString())) {
String schemaContent = apiProvider.getGraphqlSchema(apiIdentifier);
CommonUtil.writeFile(archivePath + ImportExportConstants.GRAPHQL_SCHEMA_DEFINITION_LOCATION, schemaContent);
GraphqlComplexityInfo graphqlComplexityInfo = apiProvider.getComplexityDetails(apiDtoToReturn.getId());
if (graphqlComplexityInfo.getList().size() != 0) {
GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlComplexityInfotoDTO(graphqlComplexityInfo);
CommonUtil.writeDtoToFile(archivePath + ImportExportConstants.GRAPHQL_COMPLEXITY_INFO_LOCATION, exportFormat, ImportExportConstants.GRAPHQL_COMPLEXITY, graphQLQueryComplexityInfoDTO);
}
}
// For GraphQL APIs, swagger export is not needed
if (!APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(apiType)) {
String formattedSwaggerJson = RestApiCommonUtil.retrieveSwaggerDefinition(api, apiProvider);
CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.SWAGGER_DEFINITION_LOCATION, exportFormat, formattedSwaggerJson);
}
if (log.isDebugEnabled()) {
log.debug("Meta information retrieved successfully for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion());
}
} else {
String asyncApiJson = RestApiCommonUtil.retrieveAsyncAPIDefinition(api, apiProvider);
// fetching the callback URL from asyncAPI definition.
JsonParser jsonParser = new JsonParser();
JsonObject parsedObject = jsonParser.parse(asyncApiJson).getAsJsonObject();
if (parsedObject.has(ASYNC_DEFAULT_SUBSCRIBER)) {
String callBackEndpoint = parsedObject.get(ASYNC_DEFAULT_SUBSCRIBER).getAsString();
if (!StringUtils.isEmpty(callBackEndpoint)) {
// add openAPI definition to asyncAPI
String formattedSwaggerJson = RestApiCommonUtil.generateOpenAPIForAsync(apiDtoToReturn.getName(), apiDtoToReturn.getVersion(), apiDtoToReturn.getContext(), callBackEndpoint);
CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.OPENAPI_FOR_ASYNCAPI_DEFINITION_LOCATION, exportFormat, formattedSwaggerJson);
// Adding endpoint config since adapter validates api.json for endpoint urls.
HashMap<String, Object> endpointConfig = new HashMap<>();
endpointConfig.put(API_ENDPOINT_CONFIG_PROTOCOL_TYPE, "http");
endpointConfig.put("failOver", "false");
HashMap<String, Object> productionEndpoint = new HashMap<>();
productionEndpoint.put("template_not_supported", "false");
productionEndpoint.put("url", callBackEndpoint);
HashMap<String, Object> sandboxEndpoint = new HashMap<>();
sandboxEndpoint.put("template_not_supported", "false");
sandboxEndpoint.put("url", callBackEndpoint);
endpointConfig.put(API_DATA_PRODUCTION_ENDPOINTS, productionEndpoint);
endpointConfig.put(API_DATA_SANDBOX_ENDPOINTS, sandboxEndpoint);
apiDtoToReturn.setEndpointConfig(endpointConfig);
}
}
CommonUtil.writeToYamlOrJson(archivePath + ImportExportConstants.ASYNCAPI_DEFINITION_LOCATION, exportFormat, asyncApiJson);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement apiObj = gson.toJsonTree(apiDtoToReturn);
JsonObject apiJson = (JsonObject) apiObj;
apiJson.addProperty("organizationId", organization);
CommonUtil.writeDtoToFile(archivePath + ImportExportConstants.API_FILE_LOCATION, exportFormat, ImportExportConstants.TYPE_API, apiJson);
} catch (APIManagementException e) {
throw new APIImportExportException("Error while retrieving Swagger definition for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion(), e);
} catch (IOException e) {
throw new APIImportExportException("Error while retrieving saving as YAML for API: " + apiDtoToReturn.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiDtoToReturn.getVersion(), e);
}
}
use of org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo in project carbon-apimgt by wso2.
the class GraphqlQueryAnalysisMappingUtil method fromGraphqlComplexityInfotoDTO.
/**
* Converts a GraphqlComplexityInfo object into a DTO object.
*
* @param graphqlComplexityInfo GraphqlComplexityInfo object
* @return a new GraphQLQueryComplexityInfoDTO object corresponding to given GraphqlComplexityInfo object
*/
public static GraphQLQueryComplexityInfoDTO fromGraphqlComplexityInfotoDTO(GraphqlComplexityInfo graphqlComplexityInfo) {
GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO = new GraphQLQueryComplexityInfoDTO();
List<GraphQLCustomComplexityInfoDTO> graphQLCustomComplexityInfoDTOList = new ArrayList<GraphQLCustomComplexityInfoDTO>();
for (CustomComplexityDetails customComplexityDetails : graphqlComplexityInfo.getList()) {
GraphQLCustomComplexityInfoDTO graphQLCustomComplexityInfoDTO = new GraphQLCustomComplexityInfoDTO();
graphQLCustomComplexityInfoDTO.setType(customComplexityDetails.getType());
graphQLCustomComplexityInfoDTO.setField(customComplexityDetails.getField());
graphQLCustomComplexityInfoDTO.setComplexityValue(customComplexityDetails.getComplexityValue());
graphQLCustomComplexityInfoDTOList.add(graphQLCustomComplexityInfoDTO);
}
graphQLQueryComplexityInfoDTO.setList(graphQLCustomComplexityInfoDTOList);
return graphQLQueryComplexityInfoDTO;
}
use of org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo in project carbon-apimgt by wso2.
the class GraphQLSchemaDefinition method buildSchemaWithAdditionalInfo.
/**
* build schema with additional info
*
* @param api api object
* @param graphqlComplexityInfo
* @return schemaDefinition
*/
public String buildSchemaWithAdditionalInfo(API api, GraphqlComplexityInfo graphqlComplexityInfo) {
Swagger swagger = null;
Map<String, String> scopeRoleMap = new HashMap<>();
Map<String, String> operationScopeMap = new HashMap<>();
Map<String, String> operationAuthSchemeMap = new HashMap<>();
Map<String, String> operationThrottlingMap = new HashMap<>();
String operationScopeType;
StringBuilder schemaDefinitionBuilder = new StringBuilder(api.getGraphQLSchema());
schemaDefinitionBuilder.append("\n");
StringBuilder operationScopeMappingBuilder = new StringBuilder();
StringBuilder scopeRoleMappingBuilder = new StringBuilder();
StringBuilder operationAuthSchemeMappingBuilder = new StringBuilder();
StringBuilder operationThrottlingMappingBuilder = new StringBuilder();
StringBuilder policyBuilder = new StringBuilder();
String swaggerDef = api.getSwaggerDefinition();
OpenAPI openAPI = null;
LinkedHashMap<String, Object> scopeBindings = null;
if (swaggerDef != null) {
OpenAPIParser parser = new OpenAPIParser();
openAPI = parser.readContents(swaggerDef, null, null).getOpenAPI();
}
Map<String, Object> extensions = null;
if (openAPI != null) {
extensions = openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions();
}
if (extensions != null) {
scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
}
if (swaggerDef != null) {
for (URITemplate template : api.getUriTemplates()) {
String scopeInURITemplate = template.getScope() != null ? template.getScope().getKey() : null;
if (scopeInURITemplate != null) {
operationScopeMap.put(template.getUriTemplate(), scopeInURITemplate);
if (!scopeRoleMap.containsKey(scopeInURITemplate)) {
if (scopeBindings != null) {
scopeRoleMap.put(scopeInURITemplate, scopeBindings.get(scopeInURITemplate).toString());
}
}
}
}
for (URITemplate template : api.getUriTemplates()) {
operationThrottlingMap.put(template.getUriTemplate(), template.getThrottlingTier());
operationAuthSchemeMap.put(template.getUriTemplate(), template.getAuthType());
}
if (operationScopeMap.size() > 0) {
String base64EncodedURLOperationKey;
String base64EncodedURLScope;
for (Map.Entry<String, String> entry : operationScopeMap.entrySet()) {
base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
base64EncodedURLScope = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
operationScopeType = "type " + APIConstants.SCOPE_OPERATION_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLScope + ": String\n}\n";
operationScopeMappingBuilder.append(operationScopeType);
}
schemaDefinitionBuilder.append(operationScopeMappingBuilder.toString());
}
if (scopeRoleMap.size() > 0) {
String[] roleList;
String scopeType;
String base64EncodedURLScopeKey;
String scopeRoleMappingType;
String base64EncodedURLRole;
String roleField;
for (Map.Entry<String, String> entry : scopeRoleMap.entrySet()) {
List<String> scopeRoles = new ArrayList<>();
base64EncodedURLScopeKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
scopeType = "type " + APIConstants.SCOPE_ROLE_MAPPING + "_" + base64EncodedURLScopeKey + "{\n";
StringBuilder scopeRoleBuilder = new StringBuilder(scopeType);
roleList = entry.getValue().split(",");
for (String role : roleList) {
if (!role.equals("") && !scopeRoles.contains(role)) {
base64EncodedURLRole = Base64.getUrlEncoder().withoutPadding().encodeToString(role.getBytes(Charset.defaultCharset()));
roleField = base64EncodedURLRole + ": String\n";
scopeRoleBuilder.append(roleField);
scopeRoles.add(role);
}
}
if (scopeRoles.size() > 0 && !StringUtils.isEmpty(scopeRoleBuilder.toString())) {
scopeRoleMappingType = scopeRoleBuilder.toString() + "}\n";
scopeRoleMappingBuilder.append(scopeRoleMappingType);
}
}
schemaDefinitionBuilder.append(scopeRoleMappingBuilder.toString());
}
if (operationThrottlingMap.size() > 0) {
String operationThrottlingType;
for (Map.Entry<String, String> entry : operationThrottlingMap.entrySet()) {
String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
String base64EncodedURLThrottilingTier = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
operationThrottlingType = "type " + APIConstants.OPERATION_THROTTLING_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLThrottilingTier + ": String\n}\n";
operationThrottlingMappingBuilder.append(operationThrottlingType);
}
schemaDefinitionBuilder.append(operationThrottlingMappingBuilder.toString());
}
if (operationAuthSchemeMap.size() > 0) {
String operationAuthSchemeType;
String isSecurityEnabled;
for (Map.Entry<String, String> entry : operationAuthSchemeMap.entrySet()) {
String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
if (entry.getValue().equalsIgnoreCase(APIConstants.AUTH_NO_AUTHENTICATION)) {
isSecurityEnabled = APIConstants.OPERATION_SECURITY_DISABLED;
} else {
isSecurityEnabled = APIConstants.OPERATION_SECURITY_ENABLED;
}
operationAuthSchemeType = "type " + APIConstants.OPERATION_AUTH_SCHEME_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + isSecurityEnabled + ": String\n}\n";
operationAuthSchemeMappingBuilder.append(operationAuthSchemeType);
}
schemaDefinitionBuilder.append(operationAuthSchemeMappingBuilder.toString());
}
if (operationAuthSchemeMap.size() > 0) {
// Constructing the policy definition
JSONObject jsonPolicyDefinition = policyDefinitionToJson(graphqlComplexityInfo);
String base64EncodedPolicyDefinition = Base64.getUrlEncoder().withoutPadding().encodeToString(jsonPolicyDefinition.toJSONString().getBytes(Charset.defaultCharset()));
String policyDefinition = "type " + APIConstants.GRAPHQL_ACCESS_CONTROL_POLICY + " {\n" + base64EncodedPolicyDefinition + ": String\n}\n";
policyBuilder.append(policyDefinition);
schemaDefinitionBuilder.append(policyBuilder.toString());
}
}
return schemaDefinitionBuilder.toString();
}
use of org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getGraphQLPolicyComplexityOfAPI.
/**
* Get complexity details of a given API
*
* @param apiId apiId
* @param messageContext message context
* @return Response with complexity details of the GraphQL API
*/
@Override
public Response getGraphQLPolicyComplexityOfAPI(String apiId, MessageContext messageContext) throws APIManagementException {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
API api = apiProvider.getAPIbyUUID(apiId, organization);
if (APIConstants.GRAPHQL_API.equals(api.getType())) {
GraphqlComplexityInfo graphqlComplexityInfo = apiProvider.getComplexityDetails(apiId);
GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO = GraphqlQueryAnalysisMappingUtil.fromGraphqlComplexityInfotoDTO(graphqlComplexityInfo);
return Response.ok().entity(graphQLQueryComplexityInfoDTO).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 complexity details of API : " + apiId, e, log);
} else {
String msg = "Error while retrieving complexity details of API " + apiId;
RestApiUtil.handleInternalServerError(msg, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method updateGraphQLPolicyComplexityOfAPI.
/**
* Update complexity details of a given API
*
* @param apiId apiId
* @param body GraphQLQueryComplexityInfo DTO as request body
* @param messageContext message context
* @return Response
*/
@Override
public Response updateGraphQLPolicyComplexityOfAPI(String apiId, GraphQLQueryComplexityInfoDTO body, MessageContext messageContext) throws APIManagementException {
try {
if (StringUtils.isBlank(apiId)) {
String errorMessage = "API ID cannot be empty or null.";
RestApiUtil.handleBadRequest(errorMessage, log);
}
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
String schema = apiProvider.getGraphqlSchema(apiInfo.toAPIIdentifier());
GraphqlComplexityInfo graphqlComplexityInfo = GraphqlQueryAnalysisMappingUtil.fromDTOtoValidatedGraphqlComplexityInfo(body, schema);
if (APIConstants.GRAPHQL_API.equals(existingAPI.getType())) {
apiProvider.addOrUpdateComplexityDetails(apiId, graphqlComplexityInfo);
return Response.ok().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 updating complexity details of API : " + apiId, e, log);
} else {
String errorMessage = "Error while updating complexity details of API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
Aggregations