Search in sources :

Example 31 with Tier

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

the class ApiMgtDAO method getAllAPIUsageByProvider.

/**
 * @param providerName Name of the provider
 * @return UserApplicationAPIUsage of given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get
 *                                                           UserApplicationAPIUsage for given provider
 */
public UserApplicationAPIUsage[] getAllAPIUsageByProvider(String providerName) throws APIManagementException {
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    try {
        String sqlQuery = SQLConstants.GET_APP_API_USAGE_BY_PROVIDER_SQL;
        connection = APIMgtDBUtil.getConnection();
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
        result = ps.executeQuery();
        Map<String, UserApplicationAPIUsage> userApplicationUsages = new TreeMap<String, UserApplicationAPIUsage>();
        while (result.next()) {
            int subId = result.getInt("SUBSCRIPTION_ID");
            String userId = result.getString("USER_ID");
            String application = result.getString("APPNAME");
            int appId = result.getInt("APPLICATION_ID");
            String subStatus = result.getString("SUB_STATUS");
            String subsCreateState = result.getString("SUBS_CREATE_STATE");
            String key = userId + "::" + application;
            UserApplicationAPIUsage usage = userApplicationUsages.get(key);
            if (usage == null) {
                usage = new UserApplicationAPIUsage();
                usage.setUserId(userId);
                usage.setApplicationName(application);
                usage.setAppId(appId);
                userApplicationUsages.put(key, usage);
            }
            APIIdentifier apiId = new APIIdentifier(result.getString("API_PROVIDER"), result.getString("API_NAME"), result.getString("API_VERSION"));
            SubscribedAPI apiSubscription = new SubscribedAPI(new Subscriber(userId), apiId);
            apiSubscription.setSubStatus(subStatus);
            apiSubscription.setSubCreatedStatus(subsCreateState);
            apiSubscription.setUUID(result.getString("SUB_UUID"));
            apiSubscription.setTier(new Tier(result.getString("SUB_TIER_ID")));
            Application applicationObj = new Application(result.getString("APP_UUID"));
            apiSubscription.setApplication(applicationObj);
            usage.addApiSubscriptions(apiSubscription);
        }
        return userApplicationUsages.values().toArray(new UserApplicationAPIUsage[userApplicationUsages.size()]);
    } catch (SQLException e) {
        handleException("Failed to find API Usage for :" + providerName, e);
        return null;
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) TreeMap(java.util.TreeMap) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) 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 32 with Tier

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

the class ApiMgtDAO method updateAPI.

public void updateAPI(API api, String username) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    String previousDefaultVersion = getDefaultVersion(api.getId());
    String query = SQLConstants.UPDATE_API_SQL;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        // Header change check not required here as we update API level throttling tier
        // from same call.
        // TODO review and run tier update as separate query if need.
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, api.getContext());
        String contextTemplate = api.getContextTemplate();
        // context.
        if (contextTemplate.endsWith("/" + APIConstants.VERSION_PLACEHOLDER)) {
            // Remove the {version} part from the context template.
            contextTemplate = contextTemplate.split(Pattern.quote("/" + APIConstants.VERSION_PLACEHOLDER))[0];
        }
        prepStmt.setString(2, api.getId().getApiName());
        prepStmt.setString(3, contextTemplate);
        prepStmt.setString(4, username);
        prepStmt.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
        prepStmt.setString(6, api.getApiLevelPolicy());
        prepStmt.setString(7, api.getType());
        prepStmt.setString(8, api.getGatewayVendor());
        prepStmt.setString(9, api.getUuid());
        prepStmt.execute();
        if (api.isDefaultVersion() ^ api.getId().getVersion().equals(previousDefaultVersion)) {
            // If the api is selected as default version, it is added/replaced into AM_API_DEFAULT_VERSION table
            if (api.isDefaultVersion()) {
                addUpdateAPIAsDefaultVersion(api, connection);
            } else {
                // tick is removed
                ArrayList<APIIdentifier> apiIdList = new ArrayList<APIIdentifier>() {

                    {
                        add(api.getId());
                    }
                };
                removeAPIFromDefaultVersion(apiIdList, connection);
            }
        }
        String serviceKey = api.getServiceInfo("key");
        if (StringUtils.isNotEmpty(serviceKey)) {
            int apiId = getAPIID(api.getUuid());
            int tenantID = APIUtil.getTenantId(username);
            updateAPIServiceMapping(apiId, serviceKey, api.getServiceInfo("md5"), tenantID, connection);
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException ex) {
            // Rollback failed. Exception will be thrown later for upper exception
            log.error("Failed to rollback the update API: " + api.getId(), ex);
        }
        handleException("Error while updating the API: " + api.getId() + " in the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Timestamp(java.sql.Timestamp)

Example 33 with Tier

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

the class ApiMgtDAO method initSubscribedAPI.

private void initSubscribedAPI(SubscribedAPI subscribedAPI, ResultSet resultSet) throws SQLException {
    subscribedAPI.setUUID(resultSet.getString("SUB_UUID"));
    subscribedAPI.setSubStatus(resultSet.getString("SUB_STATUS"));
    subscribedAPI.setSubCreatedStatus(resultSet.getString("SUBS_CREATE_STATE"));
    subscribedAPI.setTier(new Tier(resultSet.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
    subscribedAPI.setRequestedTier(new Tier(resultSet.getString("TIER_ID_PENDING")));
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier)

Example 34 with Tier

use of org.wso2.carbon.apimgt.api.model.Tier 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 35 with Tier

use of org.wso2.carbon.apimgt.api.model.Tier 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)

Aggregations

Tier (org.wso2.carbon.apimgt.api.model.Tier)108 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)42 Test (org.junit.Test)40 HashSet (java.util.HashSet)39 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)37 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 API (org.wso2.carbon.apimgt.api.model.API)33 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)32 HashMap (java.util.HashMap)28 Application (org.wso2.carbon.apimgt.api.model.Application)26 Test (org.testng.annotations.Test)22 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)22 Application (org.wso2.carbon.apimgt.core.models.Application)22 LinkedHashSet (java.util.LinkedHashSet)21 JSONObject (org.json.simple.JSONObject)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)20 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 BeforeTest (org.testng.annotations.BeforeTest)19