Search in sources :

Example 6 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class UserSubstitutionService method querySubstitutes.

/**
 * Query the substitution records based on substitute, assignee and enabled or disabled.
 * Pagination parameters, start, size, sort, order are allowed.
 * @return paginated list of substitution info records
 */
@GET
@Path("/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response querySubstitutes() {
    if (!subsFeatureEnabled) {
        return Response.status(405).build();
    }
    Map<String, String> queryMap = new HashedMap();
    for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
        String value = uriInfo.getQueryParameters().getFirst(entry.getKey());
        if (value != null) {
            queryMap.put(entry.getValue(), value);
        }
    }
    // validate the parameters
    try {
        // replace with tenant aware user names
        String tenantAwareUser = getTenantAwareUser(queryMap.get(SubstitutionQueryProperties.USER));
        queryMap.put(SubstitutionQueryProperties.USER, tenantAwareUser);
        String tenantAwareSub = getTenantAwareUser(queryMap.get(SubstitutionQueryProperties.SUBSTITUTE));
        queryMap.put(SubstitutionQueryProperties.SUBSTITUTE, tenantAwareSub);
        if (!isUserAuthorizedForSubstitute(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername())) {
            String loggedInUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
            if (!((queryMap.get(SubstitutionQueryProperties.USER) != null && queryMap.get(SubstitutionQueryProperties.USER).equals(loggedInUser)) || (queryMap.get(SubstitutionQueryProperties.SUBSTITUTE) != null && queryMap.get(SubstitutionQueryProperties.SUBSTITUTE).equals(loggedInUser)))) {
                throw new BPMNForbiddenException("Not allowed to view others substitution details. No sufficient permission");
            }
        }
    } catch (UserStoreException e) {
        throw new ActivitiException("Error accessing User Store for input validations", e);
    }
    // validate pagination parameters
    validatePaginationParams(queryMap);
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    List<SubstitutesDataModel> dataModelList = UserSubstitutionUtils.querySubstitutions(queryMap, tenantId);
    int totalResultCount = UserSubstitutionUtils.getQueryResultCount(queryMap, tenantId);
    SubstituteInfoCollectionResponse collectionResponse = new SubstituteInfoCollectionResponse();
    collectionResponse.setTotal(totalResultCount);
    List<SubstituteInfoResponse> responseList = new ArrayList<>();
    for (SubstitutesDataModel subsData : dataModelList) {
        SubstituteInfoResponse response = new SubstituteInfoResponse();
        response.setEnabled(subsData.isEnabled());
        response.setEndTime(subsData.getSubstitutionEnd());
        response.setStartTime(subsData.getSubstitutionStart());
        response.setSubstitute(subsData.getSubstitute());
        response.setAssignee(subsData.getUser());
        responseList.add(response);
    }
    collectionResponse.setSubstituteInfoList(responseList);
    collectionResponse.setSize(responseList.size());
    String sortType = getSortType(queryMap.get(SubstitutionQueryProperties.SORT));
    collectionResponse.setSort(sortType);
    collectionResponse.setStart(Integer.parseInt(queryMap.get(SubstitutionQueryProperties.START)));
    collectionResponse.setOrder(queryMap.get(SubstitutionQueryProperties.ORDER));
    return Response.ok(collectionResponse).build();
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) SubstitutesDataModel(org.wso2.carbon.bpmn.core.mgt.model.SubstitutesDataModel) BPMNForbiddenException(org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) HashedMap(org.apache.commons.collections.map.HashedMap) HashedMap(org.apache.commons.collections.map.HashedMap)

Example 7 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class UserSubstitutionService method changeSubstitute.

/**
 * Change the substitute of the {user}. Use following request body format.
 * {"substitute":"user"}
 * @param user
 * @param request
 * @return
 * @throws URISyntaxException
 */
@PUT
@Path("/{user}/substitute")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response changeSubstitute(@PathParam("user") String user, SubstituteRequest request) throws URISyntaxException {
    try {
        if (!subsFeatureEnabled) {
            return Response.status(405).build();
        }
        String assignee = getRequestedAssignee(user);
        String substitute = validateAndGetSubstitute(request.getSubstitute(), assignee);
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        UserSubstitutionUtils.handleChangeSubstitute(assignee, substitute, tenantId);
    } catch (UserStoreException e) {
        throw new ActivitiException("Error accessing User Store", e);
    }
    return Response.ok().build();
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 8 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class ProcessStatisticsService method taskVariationOverTime.

/**
 * Task variation of user over time i.e. tasks started and completed by the user -- User Performance
 *
 * @param assignee taskAssignee/User selected to view the user performance of task completion over time
 * @return array with the tasks started and completed of the selected user
 */
@GET
@Path("/user-performance/variation/{assignee}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResponseHolder taskVariationOverTime(@PathParam("assignee") String assignee) throws UserStoreException {
    if (!validateCurrentUser(assignee)) {
        throw new ActivitiObjectNotFoundException("User with user id " + assignee + "not defined in the system");
    }
    ResponseHolder response = new ResponseHolder();
    List list = new ArrayList();
    SimpleDateFormat ft = new SimpleDateFormat("M");
    ProcessInstanceStatInfo[] taskStatPerMonths = new ProcessInstanceStatInfo[12];
    for (int i = 0; i < taskStatPerMonths.length; i++) {
        taskStatPerMonths[i] = new ProcessInstanceStatInfo(MONTHS[i], 0, 0);
    }
    // Get completed tasks
    List<HistoricTaskInstance> taskList = BPMNOSGIService.getHistoryService().createHistoricTaskInstanceQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).finished().list();
    for (HistoricTaskInstance instance : taskList) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        int endTime = Integer.parseInt(ft.format(instance.getEndTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
        taskStatPerMonths[endTime - 1].setInstancesCompleted(taskStatPerMonths[endTime - 1].getInstancesCompleted() + 1);
    }
    // Get active/started tasks
    List<Task> taskActive = BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).active().list();
    for (Task instance : taskActive) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
    }
    // Get suspended tasks
    List<Task> taskSuspended = BPMNOSGIService.getTaskService().createTaskQuery().taskTenantId(getTenantIdStr()).taskAssignee(assignee).suspended().list();
    for (Task instance : taskSuspended) {
        int startTime = Integer.parseInt(ft.format(instance.getCreateTime()));
        taskStatPerMonths[startTime - 1].setInstancesStarted(taskStatPerMonths[startTime - 1].getInstancesStarted() + 1);
    }
    for (int i = 0; i < taskStatPerMonths.length; i++) {
        list.add(taskStatPerMonths[i]);
    }
    response.setData(list);
    return response;
}
Also used : ResponseHolder(org.wso2.carbon.bpmn.rest.model.stats.ResponseHolder) Task(org.activiti.engine.task.Task) HistoricTaskInstance(org.activiti.engine.history.HistoricTaskInstance) ProcessInstanceStatInfo(org.wso2.carbon.bpmn.rest.model.stats.ProcessInstanceStatInfo) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 9 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class BPSUserIdentityManager method checkPassword.

@Override
public Boolean checkPassword(String userId, String password) {
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userId);
    String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
    RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
    TenantManager mgr = realmService.getTenantManager();
    int tenantId = 0;
    try {
        tenantId = mgr.getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new BPMNAuthenticationException("Identity exception thrown while getting tenant ID for user : " + userNameWithTenantDomain, e);
    }
    // tenantId == -1, means an invalid tenant.
    if (tenantId == -1) {
        if (log.isDebugEnabled()) {
            log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
        }
        return false;
    }
    org.wso2.carbon.user.api.UserStoreManager userStoreManager = null;
    boolean authStatus = false;
    try {
        userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        authStatus = userStoreManager.authenticate(tenantAwareUserName, password);
    } catch (UserStoreException e) {
        throw new BPMNAuthenticationException("User store exception thrown while authenticating user : " + userNameWithTenantDomain, e);
    }
    /* IdentityService identityService = BPMNOSGIService.getIdentityService();
        authStatus = identityService.checkPassword(userName, password);*/
    if (log.isDebugEnabled()) {
        log.debug("Basic authentication request completed. " + "Username : " + userNameWithTenantDomain + ", Authentication State : " + authStatus);
    }
    return authStatus;
}
Also used : RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager)

Example 10 with UserStoreException

use of org.wso2.carbon.user.api.UserStoreException in project carbon-business-process by wso2.

the class RESTTask method execute.

@Override
public void execute(DelegateExecution execution) {
    if (method == null) {
        String error = "HTTP method for the REST task not found. Please specify the \"method\" form property.";
        throw new RESTClientException(error);
    }
    if (log.isDebugEnabled()) {
        if (serviceURL != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceURL.getValue(execution).toString());
        } else if (serviceRef != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceRef.getValue(execution).toString());
        }
    }
    RESTInvoker restInvoker = BPMNRestExtensionHolder.getInstance().getRestInvoker();
    RESTResponse response;
    String url = null;
    String bUsername = null;
    String bPassword = null;
    JsonNodeObject jsonHeaders = null;
    boolean contentAvailable = false;
    try {
        if (serviceURL != null) {
            url = serviceURL.getValue(execution).toString();
            if (basicAuthUsername != null && basicAuthPassword != null) {
                bUsername = basicAuthUsername.getValue(execution).toString();
                bPassword = basicAuthPassword.getValue(execution).toString();
            }
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            int tenantIdInt = Integer.parseInt(execution.getTenantId());
            RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
            String domain = realmService.getTenantManager().getDomain(tenantIdInt);
            Registry registry;
            Resource urlResource;
            try {
                PrivilegedCarbonContext.startTenantFlow();
                if (domain != null) {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(domain);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                } else {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                }
                if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(tenantIdInt);
                } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(tenantIdInt);
                } else {
                    String msg = "Registry type is not specified for service reference in " + getTaskDetails(execution) + ". serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                    throw new RESTClientException(msg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Reading endpoint from registry location: " + registryPath + " for task " + getTaskDetails(execution));
                }
                urlResource = registry.get(registryPath);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
            if (urlResource != null) {
                String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
                UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
                OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
                UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
                url = uep.getAddress();
                bUsername = uep.getAuthorizationUserName();
                bPassword = uep.getAuthorizationPassword();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + getTaskDetails(execution);
                throw new RESTClientException(errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided for " + getTaskDetails(execution) + ". serviceURL or serviceRef must be provided.";
            throw new RESTClientException(urlNotFoundErrorMsg);
        }
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            jsonHeaders = JSONUtils.parse(headerContent);
        }
        if (POST_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePOST(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (GET_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeGET(new URI(url), jsonHeaders, bUsername, bPassword);
        } else if (PUT_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePUT(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (DELETE_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeDELETE(new URI(url), jsonHeaders, bUsername, bPassword);
        } else {
            String errorMsg = "Unsupported http method. The REST task only supports GET, POST, PUT and DELETE operations";
            throw new RESTClientException(errorMsg);
        }
        Object output = response.getContent();
        if (output != null) {
            contentAvailable = !response.getContent().equals("");
        }
        boolean contentTypeAvailable = false;
        if (response.getContentType() != null) {
            contentTypeAvailable = true;
        }
        if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_JSON)) {
            output = JSONUtils.parse(String.valueOf(output));
        } else if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_XML)) {
            output = Utils.parse(String.valueOf(output));
        } else {
            output = StringEscapeUtils.escapeXml(String.valueOf(output));
        }
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariable(outVarName, output);
        } else if (outputMappings != null) {
            String outMappings = outputMappings.getValue(execution).toString();
            outMappings = outMappings.trim();
            String[] mappings = outMappings.split(",");
            for (String mapping : mappings) {
                String[] mappingParts = mapping.split(":");
                String varName = mappingParts[0];
                String expression = mappingParts[1];
                Object value;
                if (output instanceof JsonNodeObject) {
                    value = ((JsonNodeObject) output).jsonPath(expression);
                } else {
                    value = ((XMLDocument) output).xPath(expression);
                }
                execution.setVariable(varName, value);
            }
        } else {
            String outputNotFoundErrorMsg = "An outputVariable or outputMappings is not provided. " + "Either an output variable or output mappings  must be provided to save " + "the response.";
            throw new RESTClientException(outputNotFoundErrorMsg);
        }
        if (responseHeaderVariable != null) {
            StringBuilder headerJsonStr = new StringBuilder();
            headerJsonStr.append("{");
            String prefix = "";
            for (Header header : response.getHeaders()) {
                headerJsonStr.append(prefix);
                String name = header.getName().replaceAll("\"", "");
                String value = header.getValue().replaceAll("\"", "");
                headerJsonStr.append("\"").append(name).append("\":\"").append(value).append("\"");
                prefix = ",";
            }
            headerJsonStr.append("}");
            JsonNodeObject headerJson = JSONUtils.parse(headerJsonStr.toString());
            execution.setVariable(responseHeaderVariable.getValue(execution).toString(), headerJson);
        }
        if (httpStatusVariable != null) {
            execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus());
        }
    } catch (RegistryException | XMLStreamException | URISyntaxException | IOException | SAXException | ParserConfigurationException e) {
        String errorMessage = "Failed to execute " + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    } catch (BPMNJsonException | BPMNXmlException e) {
        String errorMessage = "Failed to extract values for output mappings, the response content" + " doesn't support the expression" + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    } catch (UserStoreException e) {
        String errorMessage = "Failed to obtain tenant domain information";
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    }
}
Also used : BPMNJsonException(org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) XMLDocument(org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument) SAXException(org.xml.sax.SAXException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Resource(org.wso2.carbon.registry.api.Resource) Registry(org.wso2.carbon.registry.api.Registry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.api.RegistryException) Header(org.apache.http.Header) XMLStreamException(javax.xml.stream.XMLStreamException) RealmService(org.wso2.carbon.user.core.service.RealmService) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) BPMNXmlException(org.wso2.carbon.bpmn.core.types.datatypes.xml.BPMNXmlException)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)21 UserRealm (org.wso2.carbon.user.api.UserRealm)10 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)6 RealmService (org.wso2.carbon.user.core.service.RealmService)6 ArrayList (java.util.ArrayList)5 SMSOTPException (org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException)5 ActivitiException (org.activiti.engine.ActivitiException)4 HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)4 UserRealm (org.wso2.carbon.user.core.UserRealm)4 UserStoreException (org.wso2.carbon.user.core.UserStoreException)4 IOException (java.io.IOException)3 List (java.util.List)3 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)3 BPMNAuthenticationException (org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException)3 BPMNForbiddenException (org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException)3 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)3 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2