Search in sources :

Example 66 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project blueocean-plugin by jenkinsci.

the class PipelineNodeTest method sequentialParallelStagesLongRun.

@Ignore("Fails on ci.jenkins.io but not locally. Reasons unclear.  Likely a timing issue.")
@Test
public void sequentialParallelStagesLongRun() throws Exception {
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), "sequential_parallel_stages_long_run_time.jenkinsfile");
    Slave s = j.createOnlineSlave();
    s.setNumExecutors(3);
    WorkflowRun run = p.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(run);
    List<String> watchedStages = Arrays.asList("first-sequential-stage", "second-sequential-stage", "third-sequential-stage");
    run = p.scheduleBuild2(0).waitForStart();
    Thread.sleep(1000);
    long loopCount = 0;
    while (run.isBuilding()) {
        PipelineNodeContainerImpl pipelineNodeContainer = new PipelineNodeContainerImpl(run, new Link("foo"));
        List<BluePipelineNode> nodes = pipelineNodeContainer.getNodes();
        for (BluePipelineNode node : nodes) {
            if (StringUtils.isEmpty(node.getFirstParent()) && watchedStages.contains(node.getDisplayName())) {
                LOGGER.error("node {} has getFirstParent null", node);
                fail("node with getFirstParent null:" + node);
            }
            // we try to find edges with id for a non existing node in the list
            List<BluePipelineNode.Edge> emptyEdges = node.getEdges().stream().filter(edge -> !nodes.stream().filter(bluePipelineNode -> bluePipelineNode.getId().equals(edge.getId())).findFirst().isPresent()).collect(Collectors.toList());
            if (!emptyEdges.isEmpty()) {
                // TODO remove this weird if but it's only to have breakpoint in IDE
                assertTrue("edges with unknown nodes" + nodes, !emptyEdges.isEmpty());
            }
        }
        LOGGER.debug("nodes size {}", nodes.size());
        if (nodes.size() != 9) {
            LOGGER.info("loop: " + loopCount + ", nodes size {}", nodes.size());
            LOGGER.info("nodes != 9 {}", nodes);
            fail("nodes != 9:  " + nodes);
        }
        Thread.sleep(100);
    }
}
Also used : CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) Arrays(java.util.Arrays) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Issue(org.jvnet.hudson.test.Issue) QueueTaskFuture(hudson.model.queue.QueueTaskFuture) URL(java.net.URL) InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) PARAMETERS_ELEMENT(io.jenkins.blueocean.rest.impl.pipeline.PipelineStepImpl.PARAMETERS_ELEMENT) StringUtils(org.apache.commons.lang3.StringUtils) RunList(hudson.util.RunList) MemoryFlowChunk(org.jenkinsci.plugins.workflow.graphanalysis.MemoryFlowChunk) Map(java.util.Map) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Jenkins(jenkins.model.Jenkins) MapsHelper(io.jenkins.blueocean.commons.MapsHelper) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) FilePath(hudson.FilePath) Result(hudson.model.Result) JSONObject(net.sf.json.JSONObject) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Optional(java.util.Optional) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) BeforeClass(org.junit.BeforeClass) SemaphoreStep(org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep) FreeStyleProject(hudson.model.FreeStyleProject) CpsFlowExecution(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution) FlowGraphTable(org.jenkinsci.plugins.workflow.support.visualization.table.FlowGraphTable) UnstableStep(org.jenkinsci.plugins.workflow.steps.UnstableStep) GitSampleRepoRule(jenkins.plugins.git.GitSampleRepoRule) Unirest(com.mashape.unirest.http.Unirest) SCMSource(jenkins.scm.api.SCMSource) Util(hudson.Util) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Description(org.hamcrest.Description) Iterator(java.util.Iterator) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Test(org.junit.Test) BranchSource(jenkins.branch.BranchSource) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Matcher(org.hamcrest.Matcher) Assert(org.junit.Assert) Slave(hudson.model.Slave) ExtensionList(hudson.ExtensionList) GitSCMSource(jenkins.plugins.git.GitSCMSource) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Slave(hudson.model.Slave) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Link(io.jenkins.blueocean.rest.hal.Link) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 67 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project CzechIdMng by bcvsolutions.

the class AbstractRoleParametrizationFormDefaultValueGenerator method getDefaultValuesByRoleDefinition.

protected IdmFormInstanceDto getDefaultValuesByRoleDefinition(IdmRoleDto roleDto, IdmGenerateValueDto valueGenerator, IdmFormInstanceDto existingEavs, DTO dto) {
    UUID formDefinitionId = roleDto.getIdentityRoleAttributeDefinition();
    // If form definition doesn't exist continue as normal
    if (formDefinitionId == null) {
        return null;
    }
    IdmFormDefinitionDto definition = roleService.getFormAttributeSubdefinition(roleDto);
    // Internal behavior #getValuesFromInstances wants default form value
    List<IdmFormValueDto> values = new ArrayList<>();
    for (IdmFormAttributeDto attribute : definition.getFormAttributes()) {
        String defaultValue = getDefaultValue(attribute, roleDto);
        // check if exists default values
        if (StringUtils.isEmpty(defaultValue)) {
            // Check given values
            List<IdmFormValueDto> existingValues = existingEavs == null ? null : // 
            existingEavs.getValues().stream().filter(existingEav -> {
                // 
                return existingEav.getFormAttribute().equals(attribute.getId());
            }).collect(// 
            Collectors.toList());
            if (existingValues != null && !existingValues.isEmpty()) {
                // Given value exist and default value doesn't exist
                values.addAll(existingValues);
            }
            continue;
        }
        if (valueGenerator.isRegenerateValue()) {
            // For regenerate just create values by default values
            String regex = this.getRegex(valueGenerator);
            String[] defaultValues = defaultValue.split(regex);
            for (String defValue : defaultValues) {
                IdmFormValueDto value = new IdmFormValueDto(attribute);
                value.setValue(defValue);
                values.add(value);
            }
        } else {
            if (existingEavs != null) {
                // With check existing values
                List<IdmFormValueDto> existingValues = existingEavs.getValues().stream().filter(existingVal -> {
                    // 
                    return existingVal.getFormAttribute().equals(attribute.getId());
                }).collect(// 
                Collectors.toList());
                if (!existingValues.isEmpty()) {
                    // If existing value isn't empty use it (given values)
                    existingValues.forEach(existingValue -> {
                        IdmFormValueDto value = new IdmFormValueDto(attribute);
                        value.setValue(existingValue.getValue(attribute.getPersistentType()));
                        values.add(value);
                    });
                    continue;
                }
            }
            // If given values is empty use default
            if (attribute.isMultiple()) {
                // Default value may be multiple, just iterate over value splited by regex
                String regex = this.getRegex(valueGenerator);
                String[] defaultValues = defaultValue.split(regex);
                for (String defValue : defaultValues) {
                    IdmFormValueDto value = new IdmFormValueDto(attribute);
                    value.setValue(defValue);
                    values.add(value);
                }
            } else {
                // If is value single valued use it as is it
                IdmFormValueDto value = new IdmFormValueDto(attribute);
                value.setValue(defaultValue);
                values.add(value);
            }
        }
    }
    return new IdmFormInstanceDto(dto, definition, values);
}
Also used : IdmRoleFormAttributeDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleFormAttributeDto) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) IdmRoleService(eu.bcvsolutions.idm.core.api.service.IdmRoleService) Autowired(org.springframework.beans.factory.annotation.Autowired) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) IdmRoleFormAttributeService(eu.bcvsolutions.idm.core.api.service.IdmRoleFormAttributeService) ArrayList(java.util.ArrayList) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) List(java.util.List) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) IdmFormDefinitionService(eu.bcvsolutions.idm.core.eav.api.service.IdmFormDefinitionService) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmGenerateValueDto(eu.bcvsolutions.idm.core.api.dto.IdmGenerateValueDto) IdmRoleFormAttributeFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleFormAttributeFilter) Assert(org.springframework.util.Assert) AbstractValueGenerator(eu.bcvsolutions.idm.core.api.generator.AbstractValueGenerator) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) ArrayList(java.util.ArrayList) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) UUID(java.util.UUID)

Example 68 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeApplication.

/**
 * Function to remove an Application from the API Store
 *
 * @param application - The Application Object that represents the Application
 * @param username
 * @throws APIManagementException
 */
@Override
public void removeApplication(Application application, String username) throws APIManagementException {
    String uuid = application.getUUID();
    Map<String, Pair<String, String>> consumerKeysOfApplication = null;
    if (application.getId() == 0 && !StringUtils.isEmpty(uuid)) {
        application = apiMgtDAO.getApplicationByUUID(uuid);
    }
    consumerKeysOfApplication = apiMgtDAO.getConsumerKeysForApplication(application.getId());
    boolean isTenantFlowStarted = false;
    int applicationId = application.getId();
    boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
    boolean isUserAppOwner;
    if (isCaseInsensitiveComparisons) {
        isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(username);
    } else {
        isUserAppOwner = application.getSubscriber().getName().equals(username);
    }
    if (!isUserAppOwner) {
        throw new APIManagementException("user: " + username + ", " + "attempted to remove application owned by: " + application.getSubscriber().getName());
    }
    try {
        String workflowExtRef;
        ApplicationWorkflowDTO workflowDTO;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        WorkflowExecutor createApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor createProductionRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        WorkflowExecutor createSandboxRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        WorkflowExecutor removeApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceByApplicationID(application.getId());
        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new ApplicationWorkflowDTO();
        } else {
            workflowDTO = (ApplicationWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
        }
        workflowDTO.setApplication(application);
        workflowDTO.setCallbackUrl(removeApplicationWFExecutor.getCallbackURL());
        workflowDTO.setUserName(this.username);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);
        // clean up pending subscription tasks
        Set<Integer> pendingSubscriptions = apiMgtDAO.getPendingSubscriptionsByApplicationId(applicationId);
        for (int subscription : pendingSubscriptions) {
            try {
                workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(subscription);
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for subscription " + subscription);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending subscription approval task: " + subscription);
            }
        }
        // cleanup pending application registration tasks
        Map<String, String> keyManagerWiseProductionKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION);
        Map<String, String> keyManagerWiseSandboxKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_SANDBOX);
        keyManagerWiseProductionKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION, keyManagerName);
                    createProductionRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for production key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending production key approval task of " + applicationId);
                }
            }
        });
        keyManagerWiseSandboxKeyStatus.forEach((keyManagerName, state) -> {
            if (WorkflowStatus.CREATED.toString().equals(state)) {
                try {
                    String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_SANDBOX, keyManagerName);
                    createSandboxRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
                } catch (APIManagementException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to get external workflow reference for sandbox key of application " + applicationId);
                } catch (WorkflowException ex) {
                    // failed cleanup processes are ignored to prevent failing the application removal process
                    log.warn("Failed to clean pending sandbox key approval task of " + applicationId);
                }
            }
        });
        if (workflowExtRef != null) {
            try {
                createApplicationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {
                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending application approval task of " + applicationId);
            }
        }
        // update attributes of the new remove workflow to be created
        workflowDTO.setStatus(WorkflowStatus.CREATED);
        workflowDTO.setCreatedTime(System.currentTimeMillis());
        workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowDTO.setExternalWorkflowReference(removeApplicationWFExecutor.generateUUID());
        removeApplicationWFExecutor.execute(workflowDTO);
        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
        appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
        appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
        appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
        appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION + " " + "for applicationID " + application.getId();
        handleException(errorMsg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        String logMessage = "Application Name: " + application.getName() + " successfully removed";
        log.debug(logMessage);
    }
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(applicationId, username, requestedTenant);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // get the workflow state once the executor is executed.
    WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
    // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
    if (wfDTO != null) {
        if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus()) || wfDTO.getStatus() == null) {
            ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
            APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
        }
    } else {
        ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
        APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
    }
    if (consumerKeysOfApplication != null && consumerKeysOfApplication.size() > 0) {
        for (Map.Entry<String, Pair<String, String>> entry : consumerKeysOfApplication.entrySet()) {
            String consumerKey = entry.getKey();
            String keyManagerName = entry.getValue().getKey();
            String keyManagerTenantDomain = entry.getValue().getValue();
            ApplicationRegistrationEvent removeEntryTrigger = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.REMOVE_APPLICATION_KEYMAPPING.name(), APIUtil.getTenantIdFromTenantDomain(keyManagerTenantDomain), keyManagerTenantDomain, application.getId(), application.getUUID(), consumerKey, application.getKeyType(), keyManagerName);
            APIUtil.sendNotification(removeEntryTrigger, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
        }
    }
}
Also used : ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 69 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty 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)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)62 List (java.util.List)46 ArrayList (java.util.ArrayList)35 Map (java.util.Map)33 Collectors (java.util.stream.Collectors)33 HashMap (java.util.HashMap)25 Set (java.util.Set)23 Collections (java.util.Collections)21 IOException (java.io.IOException)20 Arrays (java.util.Arrays)20 HashSet (java.util.HashSet)16 Optional (java.util.Optional)16 Logger (org.slf4j.Logger)16 LoggerFactory (org.slf4j.LoggerFactory)15 Collection (java.util.Collection)14 File (java.io.File)9 URI (java.net.URI)8 Comparator (java.util.Comparator)8 UUID (java.util.UUID)8 TimeUnit (java.util.concurrent.TimeUnit)7