Search in sources :

Example 16 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class SubscriptionValidationDataUtil method fromAPItoDTO.

private static APIDTO fromAPItoDTO(API model) {
    APIDTO apidto = null;
    if (model != null) {
        apidto = new APIDTO();
        apidto.setUuid(model.getApiUUID());
        apidto.setApiId(model.getApiId());
        apidto.setVersion(model.getVersion());
        apidto.setName(model.getName());
        apidto.setContext(model.getContext());
        apidto.setPolicy(model.getPolicy());
        apidto.setProvider(model.getProvider());
        apidto.setApiType(model.getApiType());
        apidto.setName(model.getName());
        apidto.setStatus(model.getStatus());
        apidto.setIsDefaultVersion(model.isDefaultVersion());
        Map<String, URLMapping> urlMappings = model.getAllResources();
        List<URLMappingDTO> urlMappingsDTO = new ArrayList<>();
        for (URLMapping urlMapping : urlMappings.values()) {
            URLMappingDTO urlMappingDTO = new URLMappingDTO();
            urlMappingDTO.setAuthScheme(urlMapping.getAuthScheme());
            urlMappingDTO.setHttpMethod(urlMapping.getHttpMethod());
            urlMappingDTO.setThrottlingPolicy(urlMapping.getThrottlingPolicy());
            urlMappingDTO.setUrlPattern(urlMapping.getUrlPattern());
            urlMappingDTO.setScopes(urlMapping.getScopes());
            urlMappingsDTO.add(urlMappingDTO);
        }
        apidto.setUrlMappings(urlMappingsDTO);
    }
    return apidto;
}
Also used : APIDTO(org.wso2.carbon.apimgt.internal.service.dto.APIDTO) URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) ArrayList(java.util.ArrayList) URLMappingDTO(org.wso2.carbon.apimgt.internal.service.dto.URLMappingDTO)

Example 17 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method setAPICategoriesToModel.

/**
 * Set API categories to API or APIProduct based on the instance type of the DTO object passes.
 *
 * @param dto   APIDTO or APIProductDTO
 * @param model API or APIProduct
 */
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
    List<String> apiCategoryNames = new ArrayList<>();
    if (dto instanceof APIDTO) {
        APIDTO apiDTO = (APIDTO) dto;
        apiCategoryNames = apiDTO.getCategories();
    } else {
        APIProductDTO apiProductDTO = (APIProductDTO) dto;
        apiCategoryNames = apiProductDTO.getCategories();
    }
    List<APICategory> apiCategories = new ArrayList<>();
    for (String categoryName : apiCategoryNames) {
        APICategory category = new APICategory();
        category.setName(categoryName);
        apiCategories.add(category);
    }
    if (model instanceof API) {
        ((API) model).setApiCategories(apiCategories);
    } else {
        ((APIProduct) model).setApiCategories(apiCategories);
    }
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 18 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ExportUtils method setAdvertiseOnlySpecificPropertiesToDTO.

/**
 * Set the properties specific to advertise only APIs
 *
 * @param apiDto               API DTO to export
 * @param originalDevPortalUrl Original DevPortal URL (redirect URL) for the original Store
 *                             (This is used for advertise only APIs).
 */
private static void setAdvertiseOnlySpecificPropertiesToDTO(APIDTO apiDto, String originalDevPortalUrl) {
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(Boolean.TRUE);
    // Change owner to original provider as the provider will be overriding after importing
    advertiseInfoDTO.setApiOwner(apiDto.getProvider());
    advertiseInfoDTO.setOriginalDevPortalUrl(originalDevPortalUrl);
    apiDto.setAdvertiseInfo(advertiseInfoDTO);
    apiDto.setMediationPolicies(null);
}
Also used : AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.AdvertiseInfoDTO)

Example 19 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO 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);
    }
}
Also used : GraphqlComplexityInfo(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) IOException(java.io.IOException) GraphQLQueryComplexityInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.GraphQLQueryComplexityInfoDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) API(org.wso2.carbon.apimgt.api.model.API) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) JsonParser(com.google.gson.JsonParser)

Example 20 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method createAPI.

@Override
public Response createAPI(APIDTO body, String oasVersion, MessageContext messageContext) throws APIManagementException {
    URI createdApiUri;
    APIDTO createdApiDTO;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        API createdApi = PublisherCommonUtils.addAPIWithGeneratedSwaggerDefinition(body, oasVersion, RestApiCommonUtil.getLoggedInUsername(), organization);
        createdApiDTO = APIMappingUtil.fromAPItoDTO(createdApi);
        // This URI used to set the location header of the POST response
        createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
        return Response.created(createdApiUri).entity(createdApiDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + body.getProvider() + "-" + body.getName() + "-" + body.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException e) {
        String errorMessage = "Error while encrypting the secret key of API : " + body.getProvider() + "-" + body.getName() + "-" + body.getVersion() + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) URISyntaxException(java.net.URISyntaxException) CryptoException(org.wso2.carbon.core.util.CryptoException) URI(java.net.URI)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10