Search in sources :

Example 21 with Provider

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

the class TestMappingUtilTestCase method testAPIListToAPIListInfoMapping.

@Test(description = "API list to API list info mapping")
void testAPIListToAPIListInfoMapping() {
    API api1 = SampleTestObjectCreator.createDefaultAPI().id("newId1").name("newName1").context("newContext1").description("newDesc1").provider("newProvider1").lifeCycleStatus("newStatus1").version("newVersion1").workflowStatus("newWorkflowStatus1").build();
    API api2 = SampleTestObjectCreator.createDefaultAPI().id("newId2").name("newName2").context("newContext2").description("newDesc2").provider("newProvider2").lifeCycleStatus("newStatus2").version("newVersion2").workflowStatus("newWorkflowStatus2").build();
    List<API> apis = new ArrayList<>();
    apis.add(api1);
    apis.add(api2);
    APIListDTO apiListDTO = MappingUtil.toAPIListDTO(apis);
    assertEquals((Integer) apis.size(), apiListDTO.getCount());
    assertEquals(api1.getId(), apiListDTO.getList().get(0).getId());
    assertEquals(api1.getName(), apiListDTO.getList().get(0).getName());
    assertEquals(api1.getContext(), apiListDTO.getList().get(0).getContext());
    assertEquals(api1.getDescription(), apiListDTO.getList().get(0).getDescription());
    assertEquals(api1.getProvider(), apiListDTO.getList().get(0).getProvider());
    assertEquals(api1.getLifeCycleStatus(), apiListDTO.getList().get(0).getLifeCycleStatus());
    assertEquals(api1.getVersion(), apiListDTO.getList().get(0).getVersion());
    assertEquals(api1.getWorkflowStatus(), apiListDTO.getList().get(0).getWorkflowStatus());
    assertEquals(api2.getId(), apiListDTO.getList().get(1).getId());
    assertEquals(api2.getName(), apiListDTO.getList().get(1).getName());
    assertEquals(api2.getContext(), apiListDTO.getList().get(1).getContext());
    assertEquals(api2.getDescription(), apiListDTO.getList().get(1).getDescription());
    assertEquals(api2.getProvider(), apiListDTO.getList().get(1).getProvider());
    assertEquals(api2.getLifeCycleStatus(), apiListDTO.getList().get(1).getLifeCycleStatus());
    assertEquals(api2.getVersion(), apiListDTO.getList().get(1).getVersion());
    assertEquals(api2.getWorkflowStatus(), apiListDTO.getList().get(1).getWorkflowStatus());
}
Also used : ArrayList(java.util.ArrayList) APIListDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO) API(org.wso2.carbon.apimgt.core.models.API) Test(org.testng.annotations.Test)

Example 22 with Provider

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

the class FileBasedApiImportExportManager method decodeApiInformationFromDirectoryStructure.

/**
 * Reads and decodes APIs and relevant information from the given set of paths
 *
 * @param apiArtifactsBasePath path to the directory with API related artifacts
 * @param newApiProvider       API newApiProvider to be updated
 * @return Set of {@link APIDetails} objects
 * @throws APIMgtEntityImportExportException if any error occurs while decoding the APIs
 */
public Set<APIDetails> decodeApiInformationFromDirectoryStructure(String apiArtifactsBasePath, String newApiProvider) throws APIMgtEntityImportExportException {
    Set<String> apiDefinitionsRootDirectoryPaths = null;
    try {
        apiDefinitionsRootDirectoryPaths = APIFileUtils.getDirectoryList(apiArtifactsBasePath);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Unable to find API definitions at: " + apiArtifactsBasePath;
        log.error(errorMsg, e);
        throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
    }
    if (apiDefinitionsRootDirectoryPaths.isEmpty()) {
        try {
            APIFileUtils.deleteDirectory(path);
        } catch (APIMgtDAOException e) {
            log.warn("Unable to remove directory " + path);
        }
        String errorMsg = "Unable to find API definitions at: " + apiArtifactsBasePath;
        throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
    }
    Set<APIDetails> apiDetailsSet = new HashSet<>();
    for (String apiDefinitionDirectoryPath : apiDefinitionsRootDirectoryPaths) {
        File apiDefinitionFile = getFileFromPrefix(apiDefinitionDirectoryPath, APIMgtConstants.APIFileUtilConstants.API_DEFINITION_FILE_PREFIX);
        File swaggerDefinitionFile = getFileFromPrefix(apiDefinitionDirectoryPath, APIMgtConstants.APIFileUtilConstants.SWAGGER_DEFINITION_FILE_PREFIX);
        API api;
        String swaggerDefinition, gatewayConfiguration;
        Set<Endpoint> endpoints;
        try {
            api = getApiDefinitionFromExtractedArchive(apiDefinitionFile.getPath());
            swaggerDefinition = getSwaggerDefinitionFromExtractedArchive(swaggerDefinitionFile.getPath());
            gatewayConfiguration = getGatewayConfigurationFromExtractedArchive(apiDefinitionDirectoryPath + File.separator + APIMgtConstants.APIFileUtilConstants.GATEWAY_CONFIGURATION_DEFINITION_FILE);
            endpoints = getEndpointsFromExtractedArchive(apiDefinitionDirectoryPath + File.separator + ENDPOINTS_ROOT_DIRECTORY, api.getName(), api.getVersion());
        } catch (APIManagementException e) {
            log.error("Error occurred while importing api from path: " + apiDefinitionDirectoryPath, e);
            // skip this API
            continue;
        }
        if (newApiProvider != null && !newApiProvider.isEmpty()) {
            // update the newApiProvider
            api = new API.APIBuilder(api).provider(newApiProvider).build();
        }
        String documentsRootDirectory = apiDefinitionDirectoryPath + File.separator + DOCUMENTS_ROOT_DIRECTORY;
        Set<DocumentInfo> documentInfoSet = getDocumentInfoFromExtractedArchive(documentsRootDirectory, api.getName(), api.getVersion());
        Set<DocumentContent> documentContents = new HashSet<>();
        for (DocumentInfo aDocumentInfo : documentInfoSet) {
            DocumentContent aDocumentContent = getDocumentContentFromExtractedArchive(aDocumentInfo, documentsRootDirectory + File.separator + aDocumentInfo.getId());
            if (aDocumentContent != null) {
                documentContents.add(aDocumentContent);
            }
        }
        InputStream thumbnailStream = null;
        try {
            thumbnailStream = APIFileUtils.getThumbnailImage(apiDefinitionDirectoryPath + File.separator + APIMgtConstants.APIFileUtilConstants.THUMBNAIL_FILE_NAME);
        } catch (APIMgtDAOException e) {
            // log and ignore
            log.error("Error occurred while reading thumbnail image.", e);
        }
        APIDetails apiDetails = new APIDetails(api, swaggerDefinition);
        apiDetails.setGatewayConfiguration(gatewayConfiguration);
        apiDetails.setEndpoints(endpoints);
        if (!documentInfoSet.isEmpty()) {
            apiDetails.addDocumentInformation(documentInfoSet);
        }
        if (!documentContents.isEmpty()) {
            apiDetails.addDocumentContents(documentContents);
        }
        if (thumbnailStream != null) {
            apiDetails.setThumbnailStream(thumbnailStream);
        }
        apiDetailsSet.add(apiDetails);
    }
    return apiDetailsSet;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) InputStream(java.io.InputStream) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) APIMgtEntityImportExportException(org.wso2.carbon.apimgt.core.exception.APIMgtEntityImportExportException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) API(org.wso2.carbon.apimgt.core.models.API) File(java.io.File) HashSet(java.util.HashSet) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 23 with Provider

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

the class FileBasedApiImportExportManager method importAndCreateAPIs.

/**
 * Imports and creates a set of new APIs to API Manager by reading and decoding the
 * input stream. Will fail if the APIs already exists
 *
 * @param uploadedApiArchiveInputStream InputStream to be read ana decoded to a set of APIs
 * @param provider                      API provider, if needs to be updated
 * @return {@link APIListDTO} object comprising of successfully imported APIs
 * @throws APIMgtEntityImportExportException if any error occurs while importing or no APIs are imported successfully
 */
public APIListDTO importAndCreateAPIs(InputStream uploadedApiArchiveInputStream, String provider) throws APIMgtEntityImportExportException {
    String apiArchiveLocation = path + File.separator + IMPORTED_APIS_DIRECTORY_NAME + ".zip";
    String archiveExtractLocation = null;
    try {
        archiveExtractLocation = APIFileUtils.extractUploadedArchive(uploadedApiArchiveInputStream, IMPORTED_APIS_DIRECTORY_NAME, apiArchiveLocation, path);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error in accessing uploaded API archive" + apiArchiveLocation;
        log.error(errorMsg, e);
        throw new APIMgtEntityImportExportException(errorMsg, e, ExceptionCodes.API_IMPORT_ERROR);
    }
    // List to contain newly created/updated APIs
    Set<APIDetails> apiDetailsSet = decodeApiInformationFromDirectoryStructure(archiveExtractLocation, provider);
    List<API> apis = new ArrayList<>();
    for (APIDetails apiDetails : apiDetailsSet) {
        try {
            apis.add(importAndCreateApi(apiDetails));
        } catch (APIManagementException e) {
            log.error("Error while importing API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
            // skip importing the API
            continue;
        }
        log.info("Successfully imported API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
    }
    try {
        APIFileUtils.deleteDirectory(path);
    } catch (APIMgtDAOException e) {
        log.warn("Unable to remove directory " + path);
    }
    // if no APIs are corrected exported, throw an error
    if (apis.isEmpty()) {
        String errorMsg = "No APIs imported successfully";
        throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
    }
    return MappingUtil.toAPIListDTO(apis);
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.core.models.API) APIMgtEntityImportExportException(org.wso2.carbon.apimgt.core.exception.APIMgtEntityImportExportException)

Example 24 with Provider

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

the class ImportApiServiceImpl method importApisPut.

/**
 * Imports an updates a set of existing APIs which have been exported as a zip file
 *
 * @param fileInputStream content stream of the zip file which contains exported API(s)
 * @param fileDetail      meta information of the zip file
 * @param provider        provider of the API (if it needs to be updated)
 * @param request         ms4j request object
 * @return List of APIs that were imported
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response importApisPut(InputStream fileInputStream, FileInfo fileDetail, String provider, Request request) throws NotFoundException {
    APIPublisher publisher = null;
    try {
        publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
        FileBasedApiImportExportManager importManager = new FileBasedApiImportExportManager(publisher, System.getProperty("java.io.tmpdir") + File.separator + "imported-api-archives-" + UUID.randomUUID().toString());
        APIListDTO apiList = importManager.importAPIs(fileInputStream, provider);
        return Response.status(Response.Status.OK).entity(apiList).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing the APIs";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) APIListDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO) FileBasedApiImportExportManager(org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager)

Example 25 with Provider

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

the class ImportApiServiceImpl method importApisPost.

/**
 * Imports a set of new APIs which have been exported as a zip file
 *
 * @param fileInputStream content stream of the zip file which contains exported API(s)
 * @param fileDetail      meta information of the zip file
 * @param provider        provider of the API (if it needs to be updated)
 * @param request         ms4j request object
 * @return List of APIs that were imported
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response importApisPost(InputStream fileInputStream, FileInfo fileDetail, String provider, Request request) throws NotFoundException {
    APIPublisher publisher = null;
    try {
        publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
        FileBasedApiImportExportManager importManager = new FileBasedApiImportExportManager(publisher, System.getProperty("java.io.tmpdir") + File.separator + "imported-api-archives-" + UUID.randomUUID().toString());
        APIListDTO apiList = importManager.importAndCreateAPIs(fileInputStream, provider);
        return Response.status(Response.Status.OK).entity(apiList).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing the APIs";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) APIListDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO) FileBasedApiImportExportManager(org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)82 ArrayList (java.util.ArrayList)70 API (org.wso2.carbon.apimgt.api.model.API)64 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)50 Test (org.junit.Test)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)45 HashMap (java.util.HashMap)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)36 IOException (java.io.IOException)35 Resource (org.wso2.carbon.registry.core.Resource)34 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)32 HashSet (java.util.HashSet)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 UserStoreException (org.wso2.carbon.user.api.UserStoreException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)27 ResultSet (java.sql.ResultSet)25 QName (javax.xml.namespace.QName)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25