Search in sources :

Example 21 with Limit

use of org.wso2.carbon.apimgt.core.models.policy.Limit in project carbon-apimgt by wso2.

the class APIPublisherImpl method searchAPIs.

/**
 * @param limit  Limit
 * @param offset Offset
 * @param query  Search query
 * @return List of APIS.
 * @throws APIManagementException If failed to formatApiSearch APIs.
 */
@Override
public List<API> searchAPIs(Integer limit, Integer offset, String query) throws APIManagementException {
    List<API> apiResults;
    String user = getUsername();
    Set<String> roles = new HashSet<>();
    try {
        // TODO: Need to validate users roles against results returned
        if (!"admin".equals(user)) {
            // Whenever call identity provider should convert pseudo name to actual name
            String userId = getIdentityProvider().getIdOfUser(user);
            roles = new HashSet<>(getIdentityProvider().getRoleIdsOfUser(userId));
        }
        if (query != null && !query.isEmpty()) {
            String[] attributes = query.split(ATTRIBUTE_DELIMITER);
            Map<String, String> attributeMap = new HashMap<>();
            boolean isFullTextSearch = false;
            String searchAttribute, searchValue;
            if (!query.contains(KEY_VALUE_DELIMITER)) {
                isFullTextSearch = true;
            } else {
                log.debug("Search query: " + query);
                for (String attribute : attributes) {
                    searchAttribute = attribute.split(KEY_VALUE_DELIMITER)[0];
                    searchValue = attribute.split(KEY_VALUE_DELIMITER)[1];
                    log.debug(searchAttribute + KEY_VALUE_DELIMITER + searchValue);
                    attributeMap.put(searchAttribute, searchValue);
                }
            }
            if (isFullTextSearch) {
                apiResults = getApiDAO().searchAPIs(roles, user, query, offset, limit);
            } else {
                log.debug("Attributes:", attributeMap.toString());
                apiResults = getApiDAO().attributeSearchAPIs(roles, user, attributeMap, offset, limit);
            }
        } else {
            apiResults = getApiDAO().getAPIs(roles, user);
        }
        return apiResults;
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while Searching the API with query " + query;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (IdentityProviderException e) {
        String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + user + "'s information";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) HashSet(java.util.HashSet)

Example 22 with Limit

use of org.wso2.carbon.apimgt.core.models.policy.Limit in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppforSubscriptionPolicy.

public static String createDefaultSiddhiAppforSubscriptionPolicy() {
    SubscriptionPolicy policy = createDefaultSubscriptionPolicy();
    RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
    String siddhiApp = "@App:name('subscription_" + policy.getPolicyName() + "')\n" + "\n@App:description('ExecutionPlan for subscription_" + policy.getPolicyName() + "')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))\n" + "define stream RequestStream (messageID string, appKey string, appTier string," + " subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string, resourceTier string," + " userId string,  apiContext string, apiVersion string, appTenant string, apiTenant string, " + "appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text'),\n" + "factory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', destination='TEST.FOO', connection.factory." + "type='topic',\n" + "connection.factory.jndi.name='TopicConnectionFactory')\n" + "define stream GlobalThrottleStream (throttleKey string, isThrottled bool" + ", expiryTimeStamp long);\n" + "\nFROM RequestStream\n" + "SELECT messageID, (subscriptionTier == '" + policy.getPolicyName() + "')" + " AS isEligible, subscriptionKey AS throttleKey, propertiesMap\n" + "INSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(" + policy.getDefaultQuotaPolicy().getLimit().getUnitTime() + " " + policy.getDefaultQuotaPolicy().getLimit().getTimeUnit() + ", 0)\n" + "select throttleKey, (count(messageID) >= " + limit.getRequestCount() + ")" + " as isThrottled, expiryTimeStamp group by throttleKey\n" + "INSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + " select * " + "insert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)

Example 23 with Limit

use of org.wso2.carbon.apimgt.core.models.policy.Limit in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromBandwidthLimitToDTO.

/**
 * Converts a Bandwidth Limit model object into a Bandwidth Limit DTO object
 *
 * @param bandwidthLimit Bandwidth Limit model object
 * @return Bandwidth Limit DTO object derived from model
 */
public static ThrottleLimitDTO fromBandwidthLimitToDTO(BandwidthLimit bandwidthLimit) {
    // done
    ThrottleLimitDTO dto = new ThrottleLimitDTO();
    dto = updateFieldsFromLimitToDTO(bandwidthLimit, dto);
    dto.setType(PolicyConstants.BANDWIDTH_LIMIT_TYPE);
    dto.setBandwidthLimit(new BandwidthLimitDTO());
    dto.getBandwidthLimit().setDataAmount(bandwidthLimit.getDataAmount());
    dto.getBandwidthLimit().setDataUnit(bandwidthLimit.getDataUnit());
    return dto;
}
Also used : ThrottleLimitDTO(org.wso2.carbon.apimgt.rest.api.admin.dto.ThrottleLimitDTO) BandwidthLimitDTO(org.wso2.carbon.apimgt.rest.api.admin.dto.BandwidthLimitDTO)

Example 24 with Limit

use of org.wso2.carbon.apimgt.core.models.policy.Limit in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromQuotaPolicyToDTO.

/**
 * Converts a Quota Policy object into a Throttle Limit DTO object
 *
 * @param quotaPolicy Quota Policy object
 * @return Throttle Limit DTO object derived from the Quota Policy object
 * @throws UnsupportedThrottleLimitTypeException - If error occurs
 */
public static ThrottleLimitDTO fromQuotaPolicyToDTO(QuotaPolicy quotaPolicy) throws UnsupportedThrottleLimitTypeException {
    Limit limit = quotaPolicy.getLimit();
    String throttleLimitType = quotaPolicy.getType();
    if (PolicyConstants.REQUEST_COUNT_TYPE.equals(throttleLimitType)) {
        if (limit instanceof RequestCountLimit) {
            RequestCountLimit requestCountLimit = (RequestCountLimit) limit;
            return fromRequestCountLimitToDTO(requestCountLimit);
        } else {
            String msg = "Throttle limit type " + throttleLimitType + " is not of type RequestCountLimit";
            log.error(msg);
            throw new UnsupportedThrottleLimitTypeException(msg, ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
        }
    } else if (PolicyConstants.BANDWIDTH_TYPE.equals(throttleLimitType)) {
        if (limit instanceof BandwidthLimit) {
            BandwidthLimit bandwidthLimit = (BandwidthLimit) limit;
            return fromBandwidthLimitToDTO(bandwidthLimit);
        } else {
            String msg = "Throttle limit type " + throttleLimitType + " is not of type BandwidthLimit";
            log.error(msg);
            throw new UnsupportedThrottleLimitTypeException(msg, ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
        }
    } else {
        String msg = "Throttle limit type " + throttleLimitType + " is not supported";
        log.error(msg);
        throw new UnsupportedThrottleLimitTypeException(msg, ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
    }
}
Also used : UnsupportedThrottleLimitTypeException(org.wso2.carbon.apimgt.rest.api.admin.exceptions.UnsupportedThrottleLimitTypeException) RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) Limit(org.wso2.carbon.apimgt.core.models.policy.Limit) RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) BandwidthLimit(org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit) BandwidthLimit(org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit)

Example 25 with Limit

use of org.wso2.carbon.apimgt.core.models.policy.Limit in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsGet.

/**
 * Retrieves all applications that qualifies for the search query
 *
 * @param query       Search query
 * @param limit       Max number of applications to return
 * @param offset      Starting position of pagination
 * @param ifNoneMatch If-None-Match header value
 * @param request     msf4j request object
 * @return A list of qualifying application DTOs as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response applicationsGet(String query, Integer limit, Integer offset, String ifNoneMatch, Request request) throws NotFoundException {
    ApplicationListDTO applicationListDTO = null;
    String username = RestApiUtil.getLoggedInUsername(request);
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    try {
        APIStore apiConsumer = RestApiUtil.getConsumer(username);
        List<Application> allMatchedApps = new ArrayList<>();
        if (StringUtils.isBlank(query)) {
            allMatchedApps = apiConsumer.getApplications(username);
        } else {
            Application application = apiConsumer.getApplicationByName(username, query);
            if (application != null) {
                allMatchedApps = new ArrayList<>();
                allMatchedApps.add(application);
            }
        }
        // allMatchedApps are already sorted to application name
        applicationListDTO = ApplicationMappingUtil.fromApplicationsToDTO(allMatchedApps, limit, offset);
        ApplicationMappingUtil.setPaginationParams(applicationListDTO, limit, offset, allMatchedApps.size());
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving applications";
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_NAME, query);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
    return Response.ok().entity(applicationListDTO).build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) ArrayList(java.util.ArrayList) Application(org.wso2.carbon.apimgt.core.models.Application) ApplicationListDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationListDTO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Aggregations

Test (org.testng.annotations.Test)29 HashMap (java.util.HashMap)26 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 RequestCountLimit (org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit)15 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)15 PreparedStatement (java.sql.PreparedStatement)14 BandwidthLimit (org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit)14 Map (java.util.Map)13 ArrayList (java.util.ArrayList)11 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)11 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)11 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)11 Event (org.wso2.siddhi.core.event.Event)11 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)11 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)8 SQLException (java.sql.SQLException)8 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)8 Limit (org.wso2.carbon.apimgt.core.models.policy.Limit)8 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)8 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)7