Search in sources :

Example 36 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project product-apim by wso2.

the class APIMgtBaseIntegrationIT method testApiSearch.

@Test
public void testApiSearch() {
    ApiCollectionApi apiCollectionApi = apiPublisherClient.buildClient(ApiCollectionApi.class);
    APIList apiList = apiCollectionApi.apisGet("", Collections.emptyMap());
    Assert.assertEquals(apiList.getCount().intValue(), 0);
}
Also used : ApiCollectionApi(org.wso2.carbon.apimgt.rest.integration.tests.publisher.api.ApiCollectionApi) APIList(org.wso2.carbon.apimgt.rest.integration.tests.publisher.model.APIList) Test(org.testng.annotations.Test)

Example 37 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class WSO2APIPublisher method getAPIUUID.

/**
 * Get API published to external Store by calling search API REST service in external store's publisher component.
 * If API exists, a non empty UUID will be returned.
 *
 * @param store         External Store
 * @param apiIdentifier API ID of the API to retrieve
 * @return UUID of the published API
 * @throws APIManagementException If an error occurs while searching the API in external store.
 */
private String getAPIUUID(APIStore store, APIIdentifier apiIdentifier) throws APIManagementException {
    String apiUUID;
    CloseableHttpResponse httpResponse = null;
    // Get Publisher REST endpoint from given store endpoint
    String storeEndpoint = getPublisherRESTURLFromStoreURL(store.getEndpoint()) + APIConstants.RestApiConstants.REST_API_PUB_RESOURCE_PATH_APIS;
    try {
        CloseableHttpClient httpclient = getHttpClient(storeEndpoint);
        URIBuilder uriBuilder = new URIBuilder(storeEndpoint);
        String searchQuery = APIConstants.RestApiConstants.PUB_SEARCH_API_QUERY_PARAMS_NAME + "\"" + apiIdentifier.getApiName() + "\"" + StringUtils.SPACE + APIConstants.RestApiConstants.PUB_SEARCH_API_QUERY_PARAMS_VERSION + "\"" + apiIdentifier.getVersion() + "\"";
        uriBuilder.addParameter(APIConstants.RestApiConstants.REST_API_PUB_SEARCH_API_QUERY, searchQuery);
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // Set Authorization Header of external store admin
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(store));
        // Call Publisher REST API of external store
        httpResponse = httpclient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        String responseString = EntityUtils.toString(entity);
        // release all resources held by the responseHttpEntity
        EntityUtils.consume(entity);
        if (evaluateResponseStatus(httpResponse)) {
            JSONParser parser = new JSONParser();
            JSONObject responseJson = (JSONObject) parser.parse(responseString);
            long apiListResultCount = (long) responseJson.get(APIConstants.RestApiConstants.PUB_API_LIST_RESPONSE_PARAMS_COUNT);
            if (apiListResultCount == 1) {
                JSONArray apiList = (JSONArray) responseJson.get(APIConstants.RestApiConstants.PUB_API_LIST_RESPONSE_PARAMS_LIST);
                JSONObject apiJson = (JSONObject) apiList.get(0);
                apiUUID = (String) apiJson.get(APIConstants.RestApiConstants.PUB_API_RESPONSE_PARAMS_ID);
                if (log.isDebugEnabled()) {
                    log.debug("API: " + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion() + " exists in external store: " + store.getName() + " with UUID: " + apiUUID);
                }
                return apiUUID;
            } else if (apiListResultCount > 1) {
                // Duplicate APIs exists
                String errorMessage = "Duplicate APIs exists in external store for API name:" + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion();
                log.error(errorMessage);
                throw new APIManagementException(errorMessage);
            }
            // Response count is 0. Hence API does not exists in external store.
            if (log.isDebugEnabled()) {
                log.debug("API: " + apiIdentifier.getApiName() + " version: " + apiIdentifier.getVersion() + " does not exists in external store: " + store.getName());
            }
        } else {
            String errorMessage = "API Search service call received unsuccessful response with status: " + httpResponse.getStatusLine().getStatusCode() + " response: " + responseString;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
    } catch (ParseException e) {
        String errorMessage = "Error while reading API response from external store for API: " + apiIdentifier.getApiName() + " version:" + apiIdentifier.getVersion();
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e);
    } catch (IOException e) {
        String errorMessage = "Error while getting API UUID from external store for API: " + apiIdentifier.getApiName() + " version:" + apiIdentifier.getVersion();
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while building URI for store endpoint: " + storeEndpoint;
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e);
    } finally {
        closeHTTPResponse(httpResponse);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 38 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class SubscriptionValidationDAO method getAllApis.

/*
     * This method can be used to retrieve all the APIs of a given tenant in the database
     *
     * @param tenantId : unique identifier of tenant
     * @return {@link List<API>}
     * */
public List<API> getAllApis(String organization) {
    String sql = SubscriptionValidationSQLConstants.GET_ALL_APIS_BY_ORGANIZATION;
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(organization)) {
        sql = sql.concat("WHERE AM_API.CONTEXT NOT LIKE '/t/%'");
    } else {
        sql = sql.concat("WHERE AM_API.CONTEXT LIKE '/t/" + organization + "%'");
    }
    List<API> apiList = new ArrayList<>();
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, organization);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    String deploymentName = resultSet.getString("DEPLOYMENT_NAME");
                    String apiType = resultSet.getString("API_TYPE");
                    String apiUuid = resultSet.getString("API_UUID");
                    API api = new API();
                    String provider = resultSet.getString("API_PROVIDER");
                    String name = resultSet.getString("API_NAME");
                    String version = resultSet.getString("API_VERSION");
                    api.setApiUUID(apiUuid);
                    api.setApiId(resultSet.getInt("API_ID"));
                    api.setVersion(version);
                    api.setProvider(provider);
                    api.setName(name);
                    api.setApiType(apiType);
                    api.setContext(resultSet.getString("CONTEXT"));
                    api.setStatus(resultSet.getString("STATUS"));
                    String revision = resultSet.getString("REVISION_UUID");
                    api.setPolicy(getAPILevelTier(connection, apiUuid, revision));
                    api.setIsDefaultVersion(isAPIDefaultVersion(connection, provider, name, version));
                    if (APIConstants.API_PRODUCT.equals(apiType)) {
                        attachURlMappingDetailsOfApiProduct(connection, api);
                        apiList.add(api);
                    } else {
                        if (StringUtils.isNotEmpty(deploymentName)) {
                            attachURLMappingDetails(connection, revision, api);
                            api.setEnvironment(deploymentName);
                            api.setRevision(revision);
                            apiList.add(api);
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        log.error("Error in loading APIs for organization : " + organization, e);
    }
    return apiList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) API(org.wso2.carbon.apimgt.api.model.subscription.API) PreparedStatement(java.sql.PreparedStatement)

Example 39 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetAllPaginatedAPIs.

@Test
public void testGetAllPaginatedAPIs() throws RegistryException, UserStoreException, APIManagementException, XMLStreamException {
    APIIdentifier apiId1 = new APIIdentifier("admin", "API1", "1.0.0");
    API api1 = new API(apiId1);
    api1.setContext("/test");
    APIIdentifier apiId2 = new APIIdentifier("admin", "API2", "1.0.0");
    API api2 = new API(apiId2);
    api2.setContext("/test1");
    PaginationContext paginationCtx = Mockito.mock(PaginationContext.class);
    PowerMockito.when(PaginationContext.getInstance()).thenReturn(paginationCtx);
    Mockito.when(paginationCtx.getLength()).thenReturn(2);
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    ServiceReferenceHolder sh = TestUtils.getServiceReferenceHolder();
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry userReg = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, -1234)).thenReturn(userReg);
    PowerMockito.when(APIUtil.getArtifactManager(userReg, APIConstants.API_KEY)).thenReturn(artifactManager);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    PowerMockito.when(amConfig.getFirstProperty(APIConstants.API_PUBLISHER_APIS_PER_PAGE)).thenReturn("2");
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tm = Mockito.mock(TenantManager.class);
    PowerMockito.when(sh.getRealmService()).thenReturn(realmService);
    PowerMockito.when(realmService.getTenantManager()).thenReturn(tm);
    PowerMockito.when(tm.getTenantId("carbon.super")).thenReturn(-1234);
    GenericArtifact genericArtifact1 = Mockito.mock(GenericArtifact.class);
    GenericArtifact genericArtifact2 = Mockito.mock(GenericArtifact.class);
    Mockito.when(APIUtil.getAPI(genericArtifact1)).thenReturn(api1);
    Mockito.when(APIUtil.getAPI(genericArtifact2)).thenReturn(api2);
    List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>();
    governanceArtifacts.add(genericArtifact1);
    governanceArtifacts.add(genericArtifact2);
    List<GovernanceArtifact> governanceArtifacts1 = new ArrayList<GovernanceArtifact>();
    PowerMockito.when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyMap(), any(Registry.class), Mockito.anyString())).thenReturn(governanceArtifacts, governanceArtifacts1);
    Map<String, Object> result = apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
    List<API> apiList = (List<API>) result.get("apis");
    Assert.assertEquals(2, apiList.size());
    Assert.assertEquals("API1", apiList.get(0).getId().getApiName());
    Assert.assertEquals("API2", apiList.get(1).getId().getApiName());
    Assert.assertEquals(2, result.get("totalLength"));
    // No APIs available
    Map<String, Object> result1 = apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
    List<API> apiList1 = (List<API>) result1.get("apis");
    Assert.assertEquals(0, apiList1.size());
    // Registry Exception while retrieving artifacts
    Mockito.when(artifactManager.findGenericArtifacts(Matchers.anyMap())).thenThrow(RegistryException.class);
    try {
        apiProvider.getAllPaginatedAPIs("carbon.super", 0, 10);
    } catch (APIManagementException e) {
        Assert.assertEquals("Failed to get all APIs", e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) PaginationContext(org.wso2.carbon.registry.core.pagination.PaginationContext) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 40 with APIList

use of org.wso2.carbon.apimgt.keymgt.model.entity.APIList in project carbon-apimgt by wso2.

the class GatewayUtils method generateAPIListDTO.

public static APIListDTO generateAPIListDTO(List<API> apiList) {
    APIListDTO apiListDTO = new APIListDTO();
    List<APIMetaDataDTO> apiMetaDataDTOList = new ArrayList<>();
    for (API api : apiList) {
        APIMetaDataDTO apiMetaDataDTO = new APIMetaDataDTO().apiId(api.getApiId()).name(api.getApiName()).version(api.getApiVersion()).apiUUID(api.getUuid()).apiType(api.getApiType()).provider(api.getApiProvider()).context(api.getContext()).isDefaultVersion(api.isDefaultVersion()).name(api.getApiName()).policy(api.getApiTier()).apiType(api.getApiType());
        apiMetaDataDTOList.add(apiMetaDataDTO);
    }
    apiListDTO.setList(apiMetaDataDTOList);
    apiListDTO.count(apiMetaDataDTOList.size());
    return apiListDTO;
}
Also used : ArrayList(java.util.ArrayList) APIListDTO(org.wso2.carbon.apimgt.rest.api.gateway.dto.APIListDTO) APIMetaDataDTO(org.wso2.carbon.apimgt.rest.api.gateway.dto.APIMetaDataDTO) API(org.wso2.carbon.apimgt.keymgt.model.entity.API)

Aggregations

ArrayList (java.util.ArrayList)33 API (org.wso2.carbon.apimgt.core.models.API)21 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)15 API (org.wso2.carbon.apimgt.api.model.API)14 Test (org.testng.annotations.Test)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 HashMap (java.util.HashMap)9 HashSet (java.util.HashSet)9 JSONObject (org.json.simple.JSONObject)9 APIComparator (org.wso2.carbon.apimgt.core.util.APIComparator)8 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)7 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)6 TreeSet (java.util.TreeSet)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)5 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 List (java.util.List)4