Search in sources :

Example 6 with ImportExportAPI

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

the class WSO2APIPublisherTestCase method testPublishAndUpdateToStore.

@Test
public void testPublishAndUpdateToStore() throws Exception {
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    Mockito.when(APIImportExportUtil.getImportExportAPI()).thenReturn(importExportAPI);
    Mockito.doReturn(new File(apiArtifactDir)).when(importExportAPI).exportAPI(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(ExportFormat.class), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.anyString());
    // Test Unauthenticated scenario for publishing API
    Mockito.doReturn(HttpStatus.SC_UNAUTHORIZED).when(statusLine).getStatusCode();
    String unauthenticatedResponse = "{\"code\":401,\"message\":\"\",\"description\":\"Unauthenticated request\"," + "\"moreInfo\":\"\",\"error\":[]}";
    PowerMockito.when(EntityUtils.toString(Matchers.any())).thenReturn(unauthenticatedResponse);
    String errorMsg = "Import API service call received unsuccessful response: " + unauthenticatedResponse + " status: " + HttpStatus.SC_UNAUTHORIZED;
    try {
        wso2APIPublisher.publishToStore(api, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertEquals(errorMsg, e.getMessage());
    }
    // Test Unauthenticated scenario for updating API
    try {
        wso2APIPublisher.updateToStore(api, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertEquals(errorMsg, e.getMessage());
    }
    // Test Successful scenario for publishing and updating API
    Mockito.doReturn(HttpStatus.SC_OK).when(statusLine).getStatusCode();
    String successResponse = "API imported successfully.";
    PowerMockito.when(EntityUtils.toString(Matchers.any())).thenReturn(successResponse);
    Assert.assertTrue("API Publish is unsuccessful", wso2APIPublisher.publishToStore(api, store));
    Assert.assertTrue("API Update is unsuccessful", wso2APIPublisher.updateToStore(api, store));
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 7 with ImportExportAPI

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

the class WSO2APIPublisher method exportAPIArchive.

/**
 * Exports API as an advertised API using APIImportExportManager.
 *
 * @param api API artifact to import
 * @return API archive
 * @throws APIManagementException If an error occurs while exporting API.
 */
private File exportAPIArchive(API api) throws APIManagementException {
    File apiArchive;
    String tenantDomain = null;
    int tenantId;
    try {
        // Get tenant domain and ID to generate the original DevPortal URL (redirect URL) for the original Store
        tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        // Export API as an archive file and set it as a multipart entity in the request
        ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
        apiArchive = importExportAPI.exportAPI(api.getUuid(), api.getId().getName(), api.getId().getVersion(), String.valueOf(api.getRevisionId()), api.getId().getProviderName(), Boolean.TRUE, ExportFormat.JSON, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, getExternalStoreRedirectURLForAPI(tenantId, api.getUuid()), api.getOrganization());
        if (log.isDebugEnabled()) {
            log.debug("API successfully exported to file: " + apiArchive.getName());
        }
    } catch (APIImportExportException e) {
        String errorMessage = "Error while exporting API: " + api.getId().getApiName() + " version: " + api.getId().getVersion();
        throw new APIManagementException(errorMessage, e);
    } catch (UserStoreException e) {
        String errorMessage = "Error while getting tenantId for tenant domain: " + tenantDomain + " when exporting API:" + api.getId().getApiName() + " version: " + api.getId().getVersion();
        throw new APIManagementException(errorMessage, e);
    }
    return apiArchive;
}
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) UserStoreException(org.wso2.carbon.user.api.UserStoreException) File(java.io.File)

Example 8 with ImportExportAPI

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

the class ApiProductsApiServiceImpl method importAPIProduct.

/**
 * Import an API Product by uploading an archive file. All relevant API Product data will be included upon the creation of
 * the API Product. Depending on the choice of the user, provider of the imported API Product will be preserved or modified.
 *
 * @param fileInputStream     UploadedInputStream input stream from the REST request
 * @param fileDetail          File details as Attachment
 * @param preserveProvider    User choice to keep or replace the API Product provider
 * @param rotateRevision      If the maximum revision number reached, undeploy the earliest revision and create a
 *                            new revision
 * @param importAPIs          Whether to import the dependent APIs or not.
 * @param overwriteAPIProduct Whether to update the API Product or not. This is used when updating already existing API Products.
 * @param overwriteAPIs       Whether to update the dependent APIs or not. This is used when updating already existing dependent APIs of an API Product.
 * @param messageContext      Message Context
 * @return API Product import response
 * @throws APIManagementException
 */
@Override
public Response importAPIProduct(InputStream fileInputStream, Attachment fileDetail, Boolean preserveProvider, Boolean rotateRevision, Boolean importAPIs, Boolean overwriteAPIProduct, Boolean overwriteAPIs, MessageContext messageContext) throws APIManagementException {
    // If importAPIs flag is not set, the default value is false
    importAPIs = importAPIs == null ? false : importAPIs;
    // Check if the URL parameter value is specified, otherwise the default value is true.
    preserveProvider = preserveProvider == null || preserveProvider;
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    String[] tokenScopes = (String[]) PhaseInterceptorChain.getCurrentMessage().getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
    ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
    // If the user need to import dependent APIs and the user has the required scope for that, allow the user to do it
    if (tokenScopes == null) {
        RestApiUtil.handleInternalServerError("Error occurred while importing the API Product", log);
        return null;
    } else {
        Boolean isRequiredScopesAvailable = Arrays.asList(tokenScopes).contains(RestApiConstants.API_IMPORT_EXPORT_SCOPE);
        if (!isRequiredScopesAvailable) {
            log.info("Since the user does not have required scope: " + RestApiConstants.API_IMPORT_EXPORT_SCOPE + ", importAPIs will be set to false");
        }
        importAPIs = importAPIs && isRequiredScopesAvailable;
    }
    // Check whether to update the API Product. If not specified, default value is false.
    overwriteAPIProduct = overwriteAPIProduct == null ? false : overwriteAPIProduct;
    // Check whether to update the dependent APIs. If not specified, default value is false.
    overwriteAPIs = overwriteAPIs == null ? false : overwriteAPIs;
    // Check if the URL parameter value is specified, otherwise the default value is true.
    preserveProvider = preserveProvider == null || preserveProvider;
    importExportAPI.importAPIProduct(fileInputStream, preserveProvider, rotateRevision, overwriteAPIProduct, overwriteAPIs, importAPIs, tokenScopes, organization);
    return Response.status(Response.Status.OK).entity("API Product imported successfully.").build();
}
Also used : ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)

Example 9 with ImportExportAPI

use of org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI 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)

Example 10 with ImportExportAPI

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

the class ApiProductsApiServiceImpl method exportAPIProduct.

/**
 * Exports an API Product from API Manager. Meta information, API Product icon, documentation, client certificates
 * and dependent APIs are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API Product.
 *
 * @param name           Name of the API Product that needs to be exported
 * @param version        Version of the API Product that needs to be exported
 * @param providerName   Provider name of the API Product that needs to be exported
 * @param format         Format of output documents. Can be YAML or JSON
 * @param preserveStatus Preserve API Product status on export
 * @param messageContext Message Context
 * @return Zipped file containing exported API Product
 * @throws APIManagementException
 */
@Override
public Response exportAPIProduct(String name, String version, String providerName, String revisionNumber, String format, Boolean preserveStatus, Boolean exportLatestRevision, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // 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;
    ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
    try {
        File file = importExportAPI.exportAPIProduct(null, name, version, providerName, revisionNumber, exportFormat, preserveStatus, true, true, exportLatestRevision, 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_PRODUCT, 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

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)10 Test (org.junit.Test)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)7 File (java.io.File)6 API (org.wso2.carbon.apimgt.api.model.API)6 ArtifactSynchronizerException (org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException)6 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)6 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)6 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 IOException (java.io.IOException)5 XMLStreamException (javax.xml.stream.XMLStreamException)5 OMException (org.apache.axiom.om.OMException)5 JSONObject (org.json.simple.JSONObject)5 APIMgtResourceAlreadyExistsException (org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException)5 BlockConditionNotFoundException (org.wso2.carbon.apimgt.api.BlockConditionNotFoundException)5 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)5 APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)5