Search in sources :

Example 6 with Usage

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

the class MonetizationUsagePublishAgent method run.

@Override
public void run() {
    Monetization monetizationImpl = null;
    APIAdmin apiAdmin = null;
    try {
        apiAdmin = new APIAdminImpl();
        monetizationImpl = apiAdmin.getMonetizationImplClass();
        monetizationUsagePublishInfo.setState(APIConstants.Monetization.RUNNING);
        monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.INPROGRESS);
        DateFormat df = new SimpleDateFormat(APIConstants.Monetization.USAGE_PUBLISH_TIME_FORMAT);
        Date dateobj = new Date();
        df.setTimeZone(TimeZone.getTimeZone(APIConstants.Monetization.USAGE_PUBLISH_TIME_ZONE));
        String currentDate = df.format(dateobj);
        long currentTimestamp = apiAdmin.getTimestamp(currentDate);
        // set the current time as starting time of the job
        monetizationUsagePublishInfo.setStartedTime(currentTimestamp);
        apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
        monetizationImpl.publishMonetizationUsageRecords(monetizationUsagePublishInfo);
    } catch (Exception e) {
        try {
            // update the state and status of the job incase of any execptions
            monetizationUsagePublishInfo.setState(APIConstants.Monetization.COMPLETED);
            monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.FAILED);
            apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
        } catch (APIManagementException ex) {
            String errorMsg = "Failed to update the state of monetization ussge publisher";
            log.error(errorMsg, ex);
        }
        String errorMsg = "Failed to publish monetization usage to billing Engine";
        log.error(errorMsg, e);
    }
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 7 with Usage

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

the class SubscriptionsApiServiceImpl method getSubscriptionUsage.

/**
 * Get monetization usage data for a subscription
 *
 * @param subscriptionId subscription Id
 * @param messageContext message context
 * @return monetization usage data for a subscription
 */
@Override
public Response getSubscriptionUsage(String subscriptionId, MessageContext messageContext) {
    if (StringUtils.isBlank(subscriptionId)) {
        String errorMessage = "Subscription ID cannot be empty or null when getting monetization usage.";
        RestApiUtil.handleBadRequest(errorMessage, log);
    }
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        Monetization monetizationImplementation = apiProvider.getMonetizationImplClass();
        Map<String, String> billingEngineUsageData = monetizationImplementation.getCurrentUsageForSubscription(subscriptionId, apiProvider);
        if (MapUtils.isEmpty(billingEngineUsageData)) {
            String errorMessage = "Billing engine usage data was not found for subscription ID : " + subscriptionId;
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
        APIMonetizationUsageDTO apiMonetizationUsageDTO = new APIMonetizationUsageDTO();
        apiMonetizationUsageDTO.setProperties(billingEngineUsageData);
        return Response.ok().entity(apiMonetizationUsageDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Failed to retrieve billing engine usage data for subscription ID : " + subscriptionId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (MonetizationException e) {
        String errorMessage = "Failed to get current usage for subscription ID : " + subscriptionId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) APIMonetizationUsageDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIMonetizationUsageDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 8 with Usage

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

the class ServiceCatalogDAO method getServices.

/**
 * Get services
 * @param filterParams Service Filter parameters
 * @param tenantId Tenant ID of the logged in user
 * @param shrink Whether to shrink the response or not
 * @return List of Services
 * @throws APIManagementException
 */
public List<ServiceEntry> getServices(ServiceFilterParams filterParams, int tenantId, boolean shrink) throws APIManagementException {
    List<ServiceEntry> serviceEntryList = new ArrayList<>();
    String query;
    boolean searchByKey = false;
    boolean searchByDefinitionType = false;
    boolean exactNameSearch = false;
    boolean exactVersionSearch = false;
    StringBuilder querySb = new StringBuilder();
    querySb.append("SELECT UUID, SERVICE_KEY, MD5, SERVICE_NAME, SERVICE_VERSION," + "   SERVICE_URL, DEFINITION_TYPE, DEFINITION_URL, DESCRIPTION, SECURITY_TYPE, MUTUAL_SSL_ENABLED," + "   CREATED_TIME, LAST_UPDATED_TIME, CREATED_BY, UPDATED_BY, SERVICE_DEFINITION FROM " + "   AM_SERVICE_CATALOG WHERE TENANT_ID = ? ");
    String whereClauseForExactNameSearch = "AND SERVICE_NAME = ? ";
    String whereClauseForNameSearch = "AND SERVICE_NAME LIKE ? ";
    String whereClauseForExactVersionSearch = "AND SERVICE_VERSION = ? ";
    String whereClauseForVersionSearch = " AND SERVICE_VERSION LIKE ? ";
    String whereClauseWithDefinitionType = " AND DEFINITION_TYPE = ? ";
    String whereClauseWithServiceKey = " AND SERVICE_KEY = ? ";
    if (filterParams.getName().startsWith("\"") && filterParams.getName().endsWith("\"")) {
        exactNameSearch = true;
        filterParams.setName(filterParams.getName().replace("\"", "").trim());
        querySb.append(whereClauseForExactNameSearch);
    } else {
        querySb.append(whereClauseForNameSearch);
    }
    if (filterParams.getVersion().startsWith("\"") && filterParams.getVersion().endsWith("\"")) {
        exactVersionSearch = true;
        filterParams.setVersion(filterParams.getVersion().replace("\"", "").trim());
        querySb.append(whereClauseForExactVersionSearch);
    } else {
        querySb.append(whereClauseForVersionSearch);
    }
    if (StringUtils.isNotEmpty(filterParams.getDefinitionType()) && StringUtils.isEmpty(filterParams.getKey())) {
        searchByDefinitionType = true;
        querySb.append(whereClauseWithDefinitionType);
    } else if (StringUtils.isNotEmpty(filterParams.getKey()) && StringUtils.isEmpty(filterParams.getDefinitionType())) {
        searchByKey = true;
        querySb.append(whereClauseWithServiceKey);
    } else if (StringUtils.isNotEmpty(filterParams.getDefinitionType()) && StringUtils.isNotEmpty(filterParams.getKey())) {
        searchByKey = true;
        searchByDefinitionType = true;
        querySb.append(whereClauseWithDefinitionType).append(whereClauseWithServiceKey);
    }
    querySb.append("ORDER BY ").append(filterParams.getSortBy()).append(" " + filterParams.getSortOrder());
    String[] keyArray = null;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        String driverName = connection.getMetaData().getDriverName();
        if (driverName.contains("Oracle") || driverName.contains("MS SQL") || driverName.contains("Microsoft")) {
            querySb.append(" OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
        } else if (driverName.contains("PostgreSQL")) {
            querySb.append(" OFFSET ? LIMIT ? ");
        } else {
            querySb.append(" LIMIT ?, ?");
        }
        query = querySb.toString();
        try (PreparedStatement ps = connection.prepareStatement(query)) {
            keyArray = filterParams.getKey().split(",");
            for (String key : keyArray) {
                ps.setInt(1, tenantId);
                if (exactNameSearch) {
                    ps.setString(2, filterParams.getName());
                } else {
                    ps.setString(2, "%" + filterParams.getName() + "%");
                }
                if (exactVersionSearch) {
                    ps.setString(3, filterParams.getVersion());
                } else {
                    ps.setString(3, "%" + filterParams.getVersion() + "%");
                }
                if (searchByKey && searchByDefinitionType) {
                    ps.setString(4, filterParams.getDefinitionType());
                    ps.setString(5, key);
                    ps.setInt(6, filterParams.getOffset());
                    ps.setInt(7, filterParams.getLimit());
                } else if (searchByKey) {
                    ps.setString(4, key);
                    ps.setInt(5, filterParams.getOffset());
                    ps.setInt(6, filterParams.getLimit());
                } else if (searchByDefinitionType) {
                    ps.setString(4, filterParams.getDefinitionType());
                    ps.setInt(5, filterParams.getOffset());
                    ps.setInt(6, filterParams.getLimit());
                } else {
                    ps.setInt(4, filterParams.getOffset());
                    ps.setInt(5, filterParams.getLimit());
                }
                try (ResultSet resultSet = ps.executeQuery()) {
                    while (resultSet.next()) {
                        ServiceEntry service = getServiceParams(resultSet, shrink);
                        List<API> usedAPIs = getServiceUsage(service.getUuid(), tenantId, connection);
                        int usage = usedAPIs != null ? usedAPIs.size() : 0;
                        service.setUsage(usage);
                        serviceEntryList.add(service);
                    }
                }
            }
        } catch (SQLException e) {
            handleException("Error while retrieving the Services", e);
        }
    } catch (SQLException e) {
        handleException("Error while retrieving the Services", e);
    }
    return serviceEntryList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry) ResultSet(java.sql.ResultSet) API(org.wso2.carbon.apimgt.api.model.API)

Example 9 with Usage

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

the class ApiMgtDAO method getSharedScopeUsage.

/**
 * Get the API and URI usages of the given shared scope
 *
 * @param uuid Id of the shared scope
 * @param tenantId tenant Id
 * @return usgaes ofr the shaerd scope
 * @throws APIManagementException If an error occurs while getting the usage details
 */
public SharedScopeUsage getSharedScopeUsage(String uuid, int tenantId) throws APIManagementException {
    SharedScopeUsage sharedScopeUsage;
    List<API> usedApiList = new ArrayList<>();
    String sharedScopeName = getSharedScopeKeyByUUID(uuid);
    if (sharedScopeName != null) {
        sharedScopeUsage = new SharedScopeUsage();
        sharedScopeUsage.setId(uuid);
        sharedScopeUsage.setName(sharedScopeName);
    } else {
        throw new APIMgtResourceNotFoundException("Shared Scope not found for scope ID: " + uuid, ExceptionCodes.from(ExceptionCodes.SHARED_SCOPE_NOT_FOUND, uuid));
    }
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement psForApiUsage = connection.prepareStatement(SQLConstants.GET_SHARED_SCOPE_API_USAGE_BY_TENANT)) {
        psForApiUsage.setString(1, uuid);
        psForApiUsage.setInt(2, tenantId);
        try (ResultSet apiUsageResultSet = psForApiUsage.executeQuery()) {
            while (apiUsageResultSet.next()) {
                String provider = apiUsageResultSet.getString("API_PROVIDER");
                String apiName = apiUsageResultSet.getString("API_NAME");
                String version = apiUsageResultSet.getString("API_VERSION");
                APIIdentifier apiIdentifier = new APIIdentifier(provider, apiName, version);
                API usedApi = new API(apiIdentifier);
                usedApi.setContext(apiUsageResultSet.getString("CONTEXT"));
                try (PreparedStatement psForUriUsage = connection.prepareStatement(SQLConstants.GET_SHARED_SCOPE_URI_USAGE_BY_TENANT)) {
                    int apiId = apiUsageResultSet.getInt("API_ID");
                    Set<URITemplate> usedUriTemplates = new LinkedHashSet<>();
                    psForUriUsage.setString(1, uuid);
                    psForUriUsage.setInt(2, tenantId);
                    psForUriUsage.setInt(3, apiId);
                    try (ResultSet uriUsageResultSet = psForUriUsage.executeQuery()) {
                        while (uriUsageResultSet.next()) {
                            URITemplate usedUriTemplate = new URITemplate();
                            usedUriTemplate.setUriTemplate(uriUsageResultSet.getString("URL_PATTERN"));
                            usedUriTemplate.setHTTPVerb(uriUsageResultSet.getString("HTTP_METHOD"));
                            usedUriTemplates.add(usedUriTemplate);
                        }
                    }
                    usedApi.setUriTemplates(usedUriTemplates);
                    usedApiList.add(usedApi);
                } catch (SQLException e) {
                    handleException("Failed to retrieve Resource usages of shared scope with scope ID " + uuid, e);
                }
            }
        }
        if (sharedScopeUsage != null) {
            sharedScopeUsage.setApis(usedApiList);
        }
        return sharedScopeUsage;
    } catch (SQLException e) {
        handleException("Failed to retrieve API usages of shared scope with scope ID" + uuid, e);
    }
    return null;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) PreparedStatement(java.sql.PreparedStatement) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) SharedScopeUsage(org.wso2.carbon.apimgt.api.model.SharedScopeUsage) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 10 with Usage

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

the class ServiceCatalogDAO method getServiceByUUID.

public ServiceEntry getServiceByUUID(String serviceId, int tenantId) throws APIManagementException {
    String query = SQLConstants.ServiceCatalogConstants.GET_SERVICE_BY_SERVICE_ID;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(query)) {
        ps.setString(1, serviceId);
        ps.setInt(2, tenantId);
        try (ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                ServiceEntry service = getServiceParams(rs, false);
                int usage = getServiceUsage(serviceId, tenantId, connection) != null ? getServiceUsage(serviceId, tenantId, connection).size() : 0;
                service.setUsage(usage);
                return service;
            }
        }
    } catch (SQLException e) {
        handleException("Error while retrieving details of Service with Id: " + serviceId, e);
    }
    return null;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 Connection (java.sql.Connection)7 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)7 SQLException (java.sql.SQLException)7 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)7 ArrayList (java.util.ArrayList)5 UserApplicationAPIUsage (org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage)5 APIAdmin (org.wso2.carbon.apimgt.api.APIAdmin)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 Application (org.wso2.carbon.apimgt.api.model.Application)4 APIAdminImpl (org.wso2.carbon.apimgt.impl.APIAdminImpl)4 DateFormat (java.text.DateFormat)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 TreeMap (java.util.TreeMap)3 MonetizationException (org.wso2.carbon.apimgt.api.MonetizationException)3 API (org.wso2.carbon.apimgt.api.model.API)3 Monetization (org.wso2.carbon.apimgt.api.model.Monetization)3 MonetizationUsagePublishInfo (org.wso2.carbon.apimgt.api.model.MonetizationUsagePublishInfo)3