Search in sources :

Example 46 with APIIdentifier

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

the class APIProviderImplTest method testGetCustomInSequences1.

@Test
public void testGetCustomInSequences1() throws Exception {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    mockSequences(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN, apiId);
    List<String> sequenceList = apiProvider.getCustomInSequences();
    Assert.assertNotNull(sequenceList);
    Assert.assertEquals(1, sequenceList.size());
    // OMException when building OMElement
    PowerMockito.when(APIUtil.buildOMElement(any(InputStream.class))).thenThrow(new OMException());
    apiProvider.getCustomOutSequences(apiId);
    // org.wso2.carbon.registry.api.RegistryException
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenReturn(registry);
    Mockito.when(registry.resourceExists(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION)).thenThrow(org.wso2.carbon.registry.api.RegistryException.class);
    String msg = "Error while processing the in in the registry";
    try {
        apiProvider.getCustomInSequences();
    } catch (APIManagementException e) {
        Assert.assertEquals(msg, e.getMessage());
    }
    // Registry Exception
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenThrow(RegistryException.class);
    String msg1 = "Error while retrieving registry for tenant -1";
    try {
        apiProvider.getCustomInSequences();
    } catch (APIManagementException e) {
        Assert.assertEquals(msg1, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) InputStream(java.io.InputStream) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 47 with APIIdentifier

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

the class APIProviderImplTest method testAddFileToDocumentation.

/**
 * This method tests adding file to documentation method.
 * @throws Exception
 *
 * @throws GovernanceException    Governance Exception.
 */
@Test
public void testAddFileToDocumentation() throws Exception {
    String apiUUID = "xxxxxxxx";
    String docUUID = "yyyyyyyy";
    APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
    Set<String> environments = new HashSet<String>();
    Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
    Tier tier = new Tier("Gold");
    Map<String, Tier> tiers = new TreeMap<>();
    tiers.put("Gold", tier);
    URITemplate uriTemplate1 = new URITemplate();
    uriTemplate1.setHTTPVerb("POST");
    uriTemplate1.setAuthType("Application");
    uriTemplate1.setUriTemplate("/add");
    uriTemplate1.setThrottlingTier("Gold");
    uriTemplates.add(uriTemplate1);
    final API api = new API(identifier);
    api.setStatus(APIConstants.CREATED);
    api.setVisibility("public");
    api.setAccessControl("all");
    api.setTransports("http,https");
    api.setContext("/test");
    api.setEnvironments(environments);
    api.setUriTemplates(uriTemplates);
    api.setOrganization("carbon.super");
    List<Documentation> documentationList = getDocumentationList();
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(api);
    String fileName = "test.txt";
    String contentType = "application/force-download";
    Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
    doc.setSourceType(DocumentSourceType.FILE);
    PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
    InputStream inputStream = Mockito.mock(InputStream.class);
    // apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
    DocumentationContent content = new DocumentationContent();
    ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
    content.setResourceFile(resourceFile);
    apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) QName(javax.xml.namespace.QName) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) TreeMap(java.util.TreeMap) DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) RealmService(org.wso2.carbon.user.core.service.RealmService) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) 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) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 48 with APIIdentifier

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

the class ApiMgtDAO method getSubscribedAPIs.

/**
 * This method returns the set of APIs for given subscriber, subscribed under the specified application.
 *
 * @param subscriber      subscriber
 * @param applicationName Application Name
 * @return Set<API>
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
 */
public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String applicationName, String groupingId) throws APIManagementException {
    Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_SQL;
    String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
    String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?" + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
    String whereClause = " AND SUB.USER_ID = ? ";
    String whereClauseCaseSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
    String whereClauseWithMultiGroupId = " AND  ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params)  AND TENANT = ?))  OR  ( SUB.USER_ID = ? ))";
    String whereClauseWithMultiGroupIdCaseInsensitive = " AND  ( (APP.APPLICATION_ID IN  (SELECT APPLICATION_ID " + "FROM AM_APPLICATION_GROUP_MAPPING  WHERE GROUP_ID IN ($params) AND TENANT = ?))  OR  ( LOWER(SUB" + ".USER_ID) = LOWER" + "(?) ))";
    try {
        connection = APIMgtDBUtil.getConnection();
        if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
            if (multiGroupAppSharingEnabled) {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithMultiGroupId;
                }
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] groupIdArr = groupingId.split(",");
                ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                int paramIndex = groupIdArr.length + 2;
                ps.setString(++paramIndex, tenantDomain);
                ps.setString(++paramIndex, subscriber.getName());
            } else {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
                } else {
                    sqlQuery += whereClauseWithGroupId;
                }
                ps = connection.prepareStatement(sqlQuery);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                ps.setString(3, groupingId);
                ps.setString(4, subscriber.getName());
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                sqlQuery += whereClauseCaseSensitive;
            } else {
                sqlQuery += whereClause;
            }
            ps = connection.prepareStatement(sqlQuery);
            int tenantId = APIUtil.getTenantId(subscriber.getName());
            ps.setInt(1, tenantId);
            ps.setString(2, applicationName);
            ps.setString(3, subscriber.getName());
        }
        result = ps.executeQuery();
        while (result.next()) {
            APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
            apiIdentifier.setUuid(result.getString("API_UUID"));
            SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
            subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
            subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
            subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
            subscribedAPI.setUUID(result.getString("SUB_UUID"));
            subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
            Application application = new Application(result.getString("APP_NAME"), subscriber);
            application.setUUID(result.getString("APP_UUID"));
            subscribedAPI.setApplication(application);
            subscribedAPIs.add(subscribedAPI);
        }
    } catch (SQLException e) {
        handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
    return subscribedAPIs;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 49 with APIIdentifier

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

the class ApiMgtDAO method deleteExternalAPIStoresDetails.

/**
 * Delete the records of external APIStore details.
 *
 * @param uuid       API uuid
 * @param apiStoreSet APIStores set
 * @return added/failed
 * @throws APIManagementException
 */
public boolean deleteExternalAPIStoresDetails(String uuid, Set<APIStore> apiStoreSet) throws APIManagementException {
    Connection conn = null;
    PreparedStatement ps = null;
    boolean state = false;
    try {
        conn = APIMgtDBUtil.getConnection();
        conn.setAutoCommit(false);
        String sqlQuery = SQLConstants.REMOVE_EXTERNAL_API_STORE_SQL;
        // Get API Id
        int apiIdentifier;
        apiIdentifier = getAPIID(uuid, conn);
        if (apiIdentifier == -1) {
            String msg = "Could not load API record for API with UUID: " + uuid;
            log.error(msg);
        }
        ps = conn.prepareStatement(sqlQuery);
        for (Object storeObject : apiStoreSet) {
            APIStore store = (APIStore) storeObject;
            ps.setInt(1, apiIdentifier);
            ps.setString(2, store.getName());
            ps.setString(3, store.getType());
            ps.addBatch();
        }
        ps.executeBatch();
        conn.commit();
        state = true;
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback deleting external apistore details ", e1);
            }
        }
        log.error("Failed to delete external apistore details", e);
        state = false;
    } catch (APIManagementException e) {
        log.error("Failed to delete external apistore details", e);
        state = false;
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, null);
    }
    return state;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) JSONObject(org.json.simple.JSONObject) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 50 with APIIdentifier

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

the class ApiMgtDAO method updateSubscription.

/**
 * This method is used to update the subscription
 *
 * @param identifier    APIIdentifier
 * @param subStatus     Subscription Status[BLOCKED/UNBLOCKED]
 * @param applicationId Application id
 * @param organization  Organization
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update subscriber
 */
public void updateSubscription(APIIdentifier identifier, String subStatus, int applicationId, String organization) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    PreparedStatement updatePs = null;
    int apiId = -1;
    try {
        conn = APIMgtDBUtil.getConnection();
        conn.setAutoCommit(false);
        String getApiQuery = SQLConstants.GET_API_ID_SQL;
        ps = conn.prepareStatement(getApiQuery);
        ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        ps.setString(2, identifier.getApiName());
        ps.setString(3, identifier.getVersion());
        resultSet = ps.executeQuery();
        if (resultSet.next()) {
            apiId = resultSet.getInt("API_ID");
        }
        if (apiId == -1) {
            String msg = "Unable to get the API ID for: " + identifier;
            log.error(msg);
            throw new APIManagementException(msg);
        }
        String subsCreateStatus = getSubscriptionCreaeteStatus(identifier, applicationId, organization, conn);
        if (APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subsCreateStatus)) {
            deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
        }
        // This query to update the AM_SUBSCRIPTION table
        String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_OF_APPLICATION_SQL;
        // Updating data to the AM_SUBSCRIPTION table
        updatePs = conn.prepareStatement(sqlQuery);
        updatePs.setString(1, subStatus);
        updatePs.setString(2, identifier.getProviderName());
        updatePs.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
        updatePs.setInt(4, apiId);
        updatePs.setInt(5, applicationId);
        updatePs.execute();
        // finally commit transaction
        conn.commit();
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback the add subscription ", e1);
            }
        }
        handleException("Failed to update subscription data ", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
        APIMgtDBUtil.closeAllConnections(updatePs, null, null);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Aggregations

APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)305 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)171 API (org.wso2.carbon.apimgt.api.model.API)160 Test (org.junit.Test)155 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)119 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)105 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)85 Resource (org.wso2.carbon.registry.core.Resource)79 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)69 ArrayList (java.util.ArrayList)68 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)56 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)48 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)46 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)46 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)44 HashSet (java.util.HashSet)41 HashMap (java.util.HashMap)40 IOException (java.io.IOException)37 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)37 JSONObject (org.json.simple.JSONObject)36