Search in sources :

Example 1 with ExportFormat

use of org.wso2.carbon.apimgt.impl.importexport.ExportFormat 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 2 with ExportFormat

use of org.wso2.carbon.apimgt.impl.importexport.ExportFormat 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 3 with ExportFormat

use of org.wso2.carbon.apimgt.impl.importexport.ExportFormat 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 4 with ExportFormat

use of org.wso2.carbon.apimgt.impl.importexport.ExportFormat in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsExportGet.

/**
 * Export an existing Application
 *
 * @param appName        Search query
 * @param appOwner       Owner of the Application
 * @param withKeys       Export keys with application
 * @param format         Export format
 * @param messageContext Message Context
 * @return Zip file containing exported Application
 */
@Override
public Response applicationsExportGet(String appName, String appOwner, Boolean withKeys, String format, MessageContext messageContext) throws APIManagementException {
    APIConsumer apiConsumer;
    Application application = null;
    if (StringUtils.isBlank(appName) || StringUtils.isBlank(appOwner)) {
        RestApiUtil.handleBadRequest("Application name or owner should not be empty or null.", log);
    }
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    String username = RestApiCommonUtil.getLoggedInUsername();
    apiConsumer = RestApiCommonUtil.getConsumer(username);
    if (appOwner != null && apiConsumer.getSubscriber(appOwner) != null) {
        application = ExportUtils.getApplicationDetails(appName, appOwner, apiConsumer);
    }
    if (application == null) {
        throw new APIManagementException("No application found with name " + appName + " owned by " + appOwner, ExceptionCodes.APPLICATION_NOT_FOUND);
    } else if (!MultitenantUtils.getTenantDomain(application.getSubscriber().getName()).equals(MultitenantUtils.getTenantDomain(username))) {
        throw new APIManagementException("Cross Tenant Exports are not allowed", ExceptionCodes.TENANT_MISMATCH);
    }
    File file = ExportUtils.exportApplication(application, apiConsumer, exportFormat, withKeys);
    return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) File(java.io.File)

Example 5 with ExportFormat

use of org.wso2.carbon.apimgt.impl.importexport.ExportFormat in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method exportAPI.

/**
 * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation,
 * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API.
 *
 * @param apiId          UUID of an API
 * @param name           Name of the API that needs to be exported
 * @param version        Version of the API that needs to be exported
 * @param providerName   Provider name of the API that needs to be exported
 * @param format         Format of output documents. Can be YAML or JSON
 * @param preserveStatus Preserve API status on export
 * @return
 */
@Override
public Response exportAPI(String apiId, String name, String version, String revisionNum, String providerName, String format, Boolean preserveStatus, Boolean exportLatestRevision, MessageContext messageContext) throws APIManagementException {
    // If not specified status is preserved by default
    preserveStatus = preserveStatus == null || preserveStatus;
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
        File file = importExportAPI.exportAPI(apiId, name, version, revisionNum, providerName, preserveStatus, exportFormat, Boolean.TRUE, Boolean.FALSE, exportLatestRevision, StringUtils.EMPTY, organization);
        return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
    } catch (APIImportExportException e) {
        throw new APIManagementException("Error while exporting " + RestApiConstants.RESOURCE_API, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Aggregations

APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 IOException (java.io.IOException)8 File (java.io.File)7 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)5 Gson (com.google.gson.Gson)3 GsonBuilder (com.google.gson.GsonBuilder)3 JsonArray (com.google.gson.JsonArray)3 API (org.wso2.carbon.apimgt.api.model.API)3 ExportFormat (org.wso2.carbon.apimgt.impl.importexport.ExportFormat)3 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)3 JsonObject (com.google.gson.JsonObject)2 JSONObject (org.json.JSONObject)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)2 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)2 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)2 JsonElement (com.google.gson.JsonElement)1 JsonParser (com.google.gson.JsonParser)1