Search in sources :

Example 66 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class APIMappingUtil method getAPIProductIdentifierFromUUID.

/**
 * Returns the APIProductIdentifier given the uuid.
 *
 * @param productId             API Product uuid
 * @param requestedTenantDomain tenant domain of the API
 * @return APIProductIdentifier which represents the given id
 * @throws APIManagementException
 */
public static APIProductIdentifier getAPIProductIdentifierFromUUID(String productId, String requestedTenantDomain) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    APIProduct product = apiProvider.getAPIProductbyUUID(productId, requestedTenantDomain);
    return product.getId();
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 67 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ExportUtils method addClientCertificatesToArchive.

/**
 * Retrieve Mutual SSL related certificates and store those in the archive directory.
 *
 * @param archivePath  Folder path to export client certificates
 * @param identifier   Identifier
 * @param tenantId     Tenant id of the user
 * @param provider     Api Provider
 * @param exportFormat Export format of file
 * @param organization Organization
 * @throws APIImportExportException If an error occurs when writing to file or retrieving certificate metadata
 */
public static void addClientCertificatesToArchive(String archivePath, Identifier identifier, int tenantId, APIProvider provider, ExportFormat exportFormat, String organization) throws APIImportExportException {
    List<ClientCertificateDTO> certificateMetadataDTOs;
    try {
        if (identifier instanceof APIProductIdentifier) {
            certificateMetadataDTOs = provider.searchClientCertificates(tenantId, null, (APIProductIdentifier) identifier, organization);
        } else {
            certificateMetadataDTOs = provider.searchClientCertificates(tenantId, null, (APIIdentifier) identifier, organization);
        }
        if (!certificateMetadataDTOs.isEmpty()) {
            String clientCertsDirectoryPath = archivePath + File.separator + ImportExportConstants.CLIENT_CERTIFICATES_DIRECTORY;
            CommonUtil.createDirectory(clientCertsDirectoryPath);
            JsonArray certificateList = getClientCertificateContentAndMetaData(certificateMetadataDTOs, clientCertsDirectoryPath);
            if (certificateList.size() > 0) {
                CommonUtil.writeDtoToFile(clientCertsDirectoryPath + ImportExportConstants.CLIENT_CERTIFICATE_FILE, exportFormat, ImportExportConstants.TYPE_CLIENT_CERTIFICATES, certificateList);
            }
        }
    } catch (IOException e) {
        throw new APIImportExportException("Error while saving as YAML or JSON", e);
    } catch (APIManagementException e) {
        throw new APIImportExportException("Error retrieving certificate meta data. tenantId [" + tenantId + "] api [" + tenantId + "]", e);
    }
}
Also used : JsonArray(com.google.gson.JsonArray) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) IOException(java.io.IOException)

Example 68 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ExportUtils method exportApiProduct.

/**
 * Exports an API Product from API Manager for a given API Product. MMeta information, API Product icon,
 * documentation, client certificates and dependent APIs are exported.
 *
 * @param apiProvider           API Provider
 * @param apiProductIdentifier  API Product Identifier
 * @param apiProductDtoToReturn API Product DTO
 * @param userName              Username
 * @param exportFormat          Format of output documents. Can be YAML or JSON
 * @param preserveStatus        Preserve API Product status on export
 * @param organization          Organization Identifier
 * @return
 * @throws APIManagementException If an error occurs while getting governance registry
 */
public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, APIProductDTO apiProductDtoToReturn, String userName, ExportFormat exportFormat, Boolean preserveStatus, boolean preserveDocs, boolean preserveCredentials, String organization) throws APIManagementException, APIImportExportException {
    int tenantId = 0;
    // Create temp location for storing API Product data
    File exportFolder = CommonUtil.createTempDirectory(apiProductIdentifier);
    String exportAPIBasePath = exportFolder.toString();
    String archivePath = exportAPIBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion());
    tenantId = APIUtil.getTenantId(userName);
    CommonUtil.createDirectory(archivePath);
    if (preserveDocs) {
        addThumbnailToArchive(archivePath, apiProductIdentifier, apiProvider);
        addDocumentationToArchive(archivePath, apiProductIdentifier, exportFormat, apiProvider, APIConstants.API_PRODUCT_IDENTIFIER_TYPE);
    }
    // Set API Product status to created if the status is not preserved
    if (!preserveStatus) {
        apiProductDtoToReturn.setState(APIProductDTO.StateEnum.CREATED);
    }
    addGatewayEnvironmentsToArchive(archivePath, apiProductDtoToReturn.getId(), exportFormat, apiProvider);
    addAPIProductMetaInformationToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider);
    addDependentAPIsToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider, userName, Boolean.TRUE, preserveDocs, preserveCredentials, organization);
    // Export mTLS authentication related certificates
    if (log.isDebugEnabled()) {
        log.debug("Mutual SSL enabled. Exporting client certificates.");
    }
    addClientCertificatesToArchive(archivePath, apiProductIdentifier, tenantId, apiProvider, exportFormat, organization);
    CommonUtil.archiveDirectory(exportAPIBasePath);
    FileUtils.deleteQuietly(new File(exportAPIBasePath));
    return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 69 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider 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 70 with APIProvider

use of org.wso2.carbon.apimgt.api.APIProvider in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIRevisions.

/**
 * Retrieve available revisions of an API
 *
 * @param apiId UUID of the API
 * @param query Search query string
 * @param messageContext    message context object
 * @return response containing list of API revisions
 */
@Override
public Response getAPIRevisions(String apiId, String query, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIRevisionListDTO apiRevisionListDTO;
        List<APIRevision> apiRevisions = apiProvider.getAPIRevisions(apiId);
        if (StringUtils.equalsIgnoreCase(query, "deployed:true")) {
            List<APIRevision> apiDeployedRevisions = new ArrayList<>();
            for (APIRevision apiRevision : apiRevisions) {
                if (!apiRevision.getApiRevisionDeploymentList().isEmpty()) {
                    apiDeployedRevisions.add(apiRevision);
                }
            }
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiDeployedRevisions);
        } else if (StringUtils.equalsIgnoreCase(query, "deployed:false")) {
            List<APIRevision> apiNotDeployedRevisions = new ArrayList<>();
            for (APIRevision apiRevision : apiRevisions) {
                if (apiRevision.getApiRevisionDeploymentList().isEmpty()) {
                    apiNotDeployedRevisions.add(apiRevision);
                }
            }
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiNotDeployedRevisions);
        } else {
            apiRevisionListDTO = APIMappingUtil.fromListAPIRevisiontoDTO(apiRevisions);
        }
        return Response.ok().entity(apiRevisionListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding retrieving API Revision for api id : " + apiId + " - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIRevisionListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionListDTO) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)207 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)198 API (org.wso2.carbon.apimgt.api.model.API)92 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 Test (org.junit.Test)82 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)82 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)73 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)65 IOException (java.io.IOException)40 ArrayList (java.util.ArrayList)36 URISyntaxException (java.net.URISyntaxException)34 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)32 URI (java.net.URI)31 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)31 JSONObject (org.json.simple.JSONObject)29 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)29 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)29 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)28 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)28 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)23