Search in sources :

Example 81 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class SubscriptionsApiServiceImpl method subscriptionsGet.

/**
 * Get all subscriptions that are of user or shared subscriptions of the user's group.
 * <p/>
 * If apiId is specified this will return the subscribed applications of that api
 * If application id is specified this will return the api subscriptions of that application
 *
 * @param apiId         api identifier
 * @param applicationId application identifier
 * @param offset        starting index of the subscription list
 * @param limit         max num of subscriptions returned
 * @param ifNoneMatch   If-None-Match header value
 * @return matched subscriptions as a list of SubscriptionDTOs
 */
@Override
public Response subscriptionsGet(String apiId, String applicationId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    Subscriber subscriber = new Subscriber(username);
    Set<SubscribedAPI> subscriptions;
    List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
    // pre-processing
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    // currently groupId is taken from the user so that groupId coming as a query parameter is not honored.
    // As a improvement, we can check admin privileges of the user and honor groupId.
    groupId = RestApiUtil.getLoggedInUserGroupId();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        SubscriptionListDTO subscriptionListDTO;
        if (!StringUtils.isEmpty(apiId)) {
            // todo : FIX properly, need to done properly with backend side pagination.
            // todo : getSubscribedIdentifiers() method should NOT be used. Appears to be too slow.
            // This will fail with an authorization failed exception if user does not have permission to access the API
            ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
            if (apiTypeWrapper.isAPIProduct()) {
                subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
            } else {
                subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
            }
            // sort by application name
            subscribedAPIList.addAll(subscriptions);
            subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
            subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
            SubscriptionMappingUtil.setPaginationParams(subscriptionListDTO, apiId, "", limit, offset, subscribedAPIList.size());
            return Response.ok().entity(subscriptionListDTO).build();
        } else if (!StringUtils.isEmpty(applicationId)) {
            Application application = apiConsumer.getApplicationByUUID(applicationId);
            if (application == null) {
                RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
                return null;
            }
            if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
            subscriptions = apiConsumer.getPaginatedSubscribedAPIsByApplication(application, offset, limit, organization);
            subscribedAPIList.addAll(subscriptions);
            subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
            return Response.ok().entity(subscriptionListDTO).build();
        } else {
            // neither apiId nor applicationId is given
            RestApiUtil.handleBadRequest("Either applicationId or apiId should be available", log);
            return null;
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Error while getting subscriptions of the user " + username, e, log);
        }
    }
    return null;
}
Also used : AdditionalSubscriptionInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoListDTO) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) WorkflowStatus(org.wso2.carbon.apimgt.api.WorkflowStatus) SubscriptionsApiService(org.wso2.carbon.apimgt.rest.api.store.v1.SubscriptionsApiService) SubscriptionMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.SubscriptionMappingUtil) SubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionListDTO) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) URISyntaxException(java.net.URISyntaxException) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) RestAPIStoreUtils(org.wso2.carbon.apimgt.rest.api.util.utils.RestAPIStoreUtils) StringUtils(org.apache.commons.lang3.StringUtils) APIMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.APIMappingUtil) ArrayList(java.util.ArrayList) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO) RestApiCommonUtil(org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil) AdditionalSubscriptionInfoMappingUtil(org.wso2.carbon.apimgt.rest.api.store.v1.mappings.AdditionalSubscriptionInfoMappingUtil) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) Map(java.util.Map) Monetization(org.wso2.carbon.apimgt.api.model.Monetization) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) URI(java.net.URI) Application(org.wso2.carbon.apimgt.api.model.Application) MapUtils(org.apache.commons.collections.MapUtils) APIMonetizationUsageDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIMonetizationUsageDTO) APIUtil(org.wso2.carbon.apimgt.impl.utils.APIUtil) Set(java.util.Set) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) List(java.util.List) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Response(javax.ws.rs.core.Response) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Comparator(java.util.Comparator) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application) SubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionListDTO)

Example 82 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAPIorAPIProductByUUIDWithoutPermissionCheck.

/**
 * Used to retrieve API/API Products without performing the visibility permission checks
 * @param uuid
 * @param organization
 * @return
 * @throws APIManagementException
 */
private ApiTypeWrapper getAPIorAPIProductByUUIDWithoutPermissionCheck(String uuid, String organization) throws APIManagementException {
    try {
        Organization org = new Organization(organization);
        DevPortalAPI devPortalApi = apiPersistenceInstance.getDevPortalAPI(org, uuid);
        if (devPortalApi != null) {
            if (APIConstants.API_PRODUCT.equalsIgnoreCase(devPortalApi.getType())) {
                APIProduct apiProduct = APIMapper.INSTANCE.toApiProduct(devPortalApi);
                apiProduct.setID(new APIProductIdentifier(devPortalApi.getProviderName(), devPortalApi.getApiName(), devPortalApi.getVersion()));
                populateAPIProductInformation(uuid, organization, apiProduct);
                return new ApiTypeWrapper(apiProduct);
            } else {
                API api = APIMapper.INSTANCE.toApi(devPortalApi);
                populateDevPortalAPIInformation(uuid, organization, api);
                populateDefaultVersion(api);
                api = addTiersToAPI(api, organization);
                return new ApiTypeWrapper(api);
            }
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (APIPersistenceException | OASPersistenceException | ParseException e) {
        String msg = "Failed to get API";
        throw new APIManagementException(msg, e);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ParseException(org.json.simple.parser.ParseException)

Example 83 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeSubscription.

@Override
public void removeSubscription(Identifier identifier, String userId, int applicationId, String organization) throws APIManagementException {
    APIIdentifier apiIdentifier = null;
    APIProductIdentifier apiProdIdentifier = null;
    if (identifier instanceof APIIdentifier) {
        apiIdentifier = (APIIdentifier) identifier;
    }
    if (identifier instanceof APIProductIdentifier) {
        apiProdIdentifier = (APIProductIdentifier) identifier;
    }
    String applicationName = apiMgtDAO.getApplicationNameFromId(applicationId);
    try {
        SubscriptionWorkflowDTO workflowDTO;
        WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor removeSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        String workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(identifier, applicationId, organization);
        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new SubscriptionWorkflowDTO();
        } else {
            workflowDTO = (SubscriptionWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
            // set tiername to the workflowDTO only when workflows are enabled
            SubscribedAPI subscription = apiMgtDAO.getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference()));
            workflowDTO.setTierName(subscription.getTier().getName());
        }
        workflowDTO.setApiProvider(identifier.getProviderName());
        API api = null;
        APIProduct product = null;
        String context = null;
        ApiTypeWrapper wrapper;
        if (apiIdentifier != null) {
            // The API is retrieved without visibility permission check, since the subscribers should be allowed
            // to delete already existing subscriptions made for restricted APIs
            wrapper = getAPIorAPIProductByUUIDWithoutPermissionCheck(apiIdentifier.getUUID(), organization);
            api = wrapper.getApi();
            context = api.getContext();
        } else if (apiProdIdentifier != null) {
            // The API Product is retrieved without visibility permission check, since the subscribers should be
            // allowe to delete already existing subscriptions made for restricted API Products
            wrapper = getAPIorAPIProductByUUIDWithoutPermissionCheck(apiProdIdentifier.getUUID(), organization);
            product = wrapper.getApiProduct();
            context = product.getContext();
        }
        workflowDTO.setApiContext(context);
        workflowDTO.setApiName(identifier.getName());
        workflowDTO.setApiVersion(identifier.getVersion());
        workflowDTO.setApplicationName(applicationName);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);
        workflowDTO.setExternalWorkflowReference(workflowExtRef);
        workflowDTO.setSubscriber(userId);
        workflowDTO.setCallbackUrl(removeSubscriptionWFExecutor.getCallbackURL());
        workflowDTO.setApplicationId(applicationId);
        workflowDTO.setMetadata(WorkflowConstants.PayloadConstants.API_ID, String.valueOf(identifier.getId()));
        String status = null;
        if (apiIdentifier != null) {
            status = apiMgtDAO.getSubscriptionStatus(apiIdentifier.getUUID(), applicationId);
        } else if (apiProdIdentifier != null) {
            status = apiMgtDAO.getSubscriptionStatus(apiProdIdentifier.getUUID(), applicationId);
        }
        if (APIConstants.SubscriptionStatus.ON_HOLD.equals(status)) {
            try {
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the deletion process
                log.warn("Failed to clean pending subscription approval task");
            }
        }
        // update attributes of the new remove workflow to be created
        workflowDTO.setStatus(WorkflowStatus.CREATED);
        workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        workflowDTO.setCreatedTime(System.currentTimeMillis());
        workflowDTO.setExternalWorkflowReference(removeSubscriptionWFExecutor.generateUUID());
        Tier tier = null;
        if (api != null) {
            Set<Tier> policies = api.getAvailableTiers();
            Iterator<Tier> iterator = policies.iterator();
            boolean isPolicyAllowed = false;
            while (iterator.hasNext()) {
                Tier policy = iterator.next();
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
        } else if (product != null) {
            Set<Tier> policies = product.getAvailableTiers();
            Iterator<Tier> iterator = policies.iterator();
            boolean isPolicyAllowed = false;
            while (iterator.hasNext()) {
                Tier policy = iterator.next();
                if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
                    tier = policy;
                }
            }
        }
        if (api != null) {
            // check whether monetization is enabled for API and tier plan is commercial
            if (api.getMonetizationStatus() && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                removeSubscriptionWFExecutor.deleteMonetizedSubscription(workflowDTO, api);
            } else {
                removeSubscriptionWFExecutor.execute(workflowDTO);
            }
        } else if (product != null) {
            // check whether monetization is enabled for API product and tier plan is commercial
            if (product.getMonetizationStatus() && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
                removeSubscriptionWFExecutor.deleteMonetizedSubscription(workflowDTO, product);
            } else {
                removeSubscriptionWFExecutor.execute(workflowDTO);
            }
        }
        JSONObject subsLogObject = new JSONObject();
        subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
        subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, applicationId);
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION + " for resource " + identifier.toString();
        handleException(errorMsg, e);
    }
    if (log.isDebugEnabled()) {
        String logMessage = "Subscription removed from app " + applicationName + " by " + userId + " For Id: " + identifier.toString();
        log.debug(logMessage);
    }
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) Tier(org.wso2.carbon.apimgt.api.model.Tier) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) JSONObject(org.json.simple.JSONObject) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) Iterator(java.util.Iterator) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 84 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class APIUtil method checkPermission.

/**
 * Checks whether the specified user has the specified permission.
 *
 * @param username   A username
 * @param permission A valid Carbon permission
 * @throws APIManagementException If the user does not have the specified permission or if an error occurs
 */
public static void checkPermission(String username, String permission) throws APIManagementException {
    if (username == null) {
        throw new APIManagementException("Attempt to execute privileged operation as" + " the anonymous user");
    }
    if (isPermissionCheckDisabled()) {
        log.debug("Permission verification is disabled by APIStore configuration");
        return;
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    boolean authorized;
    try {
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authorized = manager.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission, CarbonConstants.UI_PERMISSION_ACTION);
        } else {
            // store), the user realm will be null.
            if (ServiceReferenceHolder.getUserRealm() == null) {
                ServiceReferenceHolder.setUserRealm((UserRealm) ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId));
            }
            authorized = AuthorizationManager.getInstance().isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission);
        }
        if (!authorized) {
            throw new APIManagementException("User '" + username + "' does not have the " + "required permission: " + permission);
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while checking the user:" + username + " authorized or not", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 85 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class APIUtil method loadloadTenantAPIRXT.

/**
 * Load the  API RXT to the registry for tenants
 *
 * @param tenant
 * @param tenantID
 * @throws APIManagementException
 */
public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
            if (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)29 HashSet (java.util.HashSet)18 HashMap (java.util.HashMap)17 ArrayList (java.util.ArrayList)16 Test (org.testng.annotations.Test)16 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 API (org.wso2.carbon.apimgt.core.models.API)15 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)15 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)13 Map (java.util.Map)12 Resource (org.wso2.carbon.registry.core.Resource)12 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)12 API (org.wso2.carbon.apimgt.api.model.API)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)9 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)9 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)8