Search in sources :

Example 16 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project carbon-apimgt by wso2.

the class RestApiCommonUtilTest method testGetLoggedInUserTenantDomain.

@Test
public void testGetLoggedInUserTenantDomain() {
    String defaultTenantDomain = "wso2.com";
    System.setProperty(CarbonBaseConstants.CARBON_HOME, "");
    PowerMockito.mockStatic(CarbonContext.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    when(carbonContext.getTenantDomain()).thenReturn(defaultTenantDomain);
    String loggedInUsername = RestApiCommonUtil.getLoggedInUserTenantDomain();
    Assert.assertEquals(defaultTenantDomain, loggedInUsername);
}
Also used : CarbonContext(org.wso2.carbon.context.CarbonContext) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 17 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project core-util by WSO2Telco.

the class UserAuthorizationValidator method isAuthorizedRole.

public boolean isAuthorizedRole(String userName, Set<String> allowedRolesSet) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    try {
        RealmConfiguration realmConfiguration = new RealmConfiguration();
        String[] currentUserRoles = realmService.getUserRealm(realmConfiguration).getUserStoreManager().getRoleListOfUser(userName);
        List<String> currentUserRolesList = Arrays.asList(currentUserRoles);
        Iterator<String> iterator = allowedRolesSet.iterator();
        while (iterator.hasNext()) {
            String allowedRole = iterator.next();
            if (currentUserRolesList.contains(allowedRole)) {
                return true;
            }
        }
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("authorization failed for user : " + userName, e);
        return false;
    }
    log.error("authorization failed for user : " + userName);
    return false;
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) RealmService(org.wso2.carbon.user.core.service.RealmService) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext)

Example 18 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project carbon-business-process by wso2.

the class PublishProcessVariablesService method saveDASconfigInfo.

/**
 * Save DAS configuration details (received from PC), in config registry
 *
 * @param dasConfigDetailsJSONString Details of analytics configuration with WSO2 DAS as a JSON string
 * @throws RegistryException Throws RegistryException if error occurred in accessing registry
 * @throws IOException       Throws IOException if an error occurred in hadling json content
 */
private void saveDASconfigInfo(String dasConfigDetailsJSONString) throws RegistryException, IOException {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    Registry configRegistry = carbonContext.getRegistry(RegistryType.SYSTEM_CONFIGURATION);
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode dasConfigDetailsJOb = objectMapper.readTree(dasConfigDetailsJSONString);
    String processDefinitionId = dasConfigDetailsJOb.get(AnalyticsPublisherConstants.PROCESS_DEFINITION_ID).textValue();
    // create a new resource (text file) to keep process variables
    Resource procVariableJsonResource = configRegistry.newResource();
    procVariableJsonResource.setContent(dasConfigDetailsJSONString);
    procVariableJsonResource.setMediaType(MediaType.APPLICATION_JSON);
    configRegistry.put(AnalyticsPublisherConstants.REG_PATH_BPMN_ANALYTICS + processDefinitionId + "/" + AnalyticsPublisherConstants.ANALYTICS_CONFIG_FILE_NAME, procVariableJsonResource);
}
Also used : Resource(org.wso2.carbon.registry.api.Resource) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) JsonNode(com.fasterxml.jackson.databind.JsonNode) Registry(org.wso2.carbon.registry.api.Registry) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 19 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project carbon-business-process by wso2.

the class PublishProcessVariablesService method deleteDASConfigInfo.

/**
 * Delete DAS configuration details (received from PC), from config registry
 *
 * @param processDefinitionIdJSONString JSON string contains process definition id
 * @throws RegistryException Throws RegistryException if error occurred in accessing registry
 * @throws IOException       Throws IOException if an error occurred in hadling json content
 */
private void deleteDASConfigInfo(String processDefinitionIdJSONString) throws RegistryException, IOException {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    Registry configRegistry = carbonContext.getRegistry(RegistryType.SYSTEM_CONFIGURATION);
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode dasConfigDetailsJOb = objectMapper.readTree(processDefinitionIdJSONString);
    String processDefinitionId = dasConfigDetailsJOb.get(AnalyticsPublisherConstants.PROCESS_DEFINITION_ID).textValue();
    configRegistry.delete(AnalyticsPublisherConstants.REG_PATH_BPMN_ANALYTICS + processDefinitionId + "/" + AnalyticsPublisherConstants.ANALYTICS_CONFIG_FILE_NAME);
}
Also used : PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) JsonNode(com.fasterxml.jackson.databind.JsonNode) Registry(org.wso2.carbon.registry.api.Registry) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 20 with CarbonContext

use of org.wso2.carbon.context.CarbonContext in project carbon-business-process by wso2.

the class ProcessInstanceService method startInstance.

@POST
@Path("/")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response startInstance(ProcessInstanceCreateRequest processInstanceCreateRequest) {
    if (log.isDebugEnabled()) {
        log.debug("ProcessInstanceCreateRequest:" + processInstanceCreateRequest.getProcessDefinitionId());
        log.debug(" processInstanceCreateRequest.getVariables().size():" + processInstanceCreateRequest.getVariables().size());
    }
    if (processInstanceCreateRequest.getProcessDefinitionId() == null && processInstanceCreateRequest.getProcessDefinitionKey() == null && processInstanceCreateRequest.getMessage() == null) {
        throw new ActivitiIllegalArgumentException("Either processDefinitionId, processDefinitionKey or message is required.");
    }
    int paramsSet = ((processInstanceCreateRequest.getProcessDefinitionId() != null) ? 1 : 0) + ((processInstanceCreateRequest.getProcessDefinitionKey() != null) ? 1 : 0) + ((processInstanceCreateRequest.getMessage() != null) ? 1 : 0);
    if (paramsSet > 1) {
        throw new ActivitiIllegalArgumentException("Only one of processDefinitionId, processDefinitionKey or message should be set.");
    }
    if (processInstanceCreateRequest.isCustomTenantSet()) {
        // Tenant-id can only be used with either key or message
        if (processInstanceCreateRequest.getProcessDefinitionId() != null) {
            throw new ActivitiIllegalArgumentException("TenantId can only be used with either processDefinitionKey or message.");
        }
    } else {
        // if no tenantId, it must be from definitionId
        if (processInstanceCreateRequest.getProcessDefinitionId() == null) {
            throw new ActivitiIllegalArgumentException("TenantId should be specified to be used with either " + "processDefinitionKey or message.");
        }
    }
    // Have to add the validation part here
    if (!isValidUserToStartProcess(processInstanceCreateRequest)) {
        throw new RestApiBasicAuthenticationException("User doesn't have the necessary permission to start the process");
    }
    if (processInstanceCreateRequest.getSkipInstanceCreation() || processInstanceCreateRequest.getSkipInstanceCreationIfExist()) {
        ProcessInstanceQueryRequest processInstanceQueryRequest = processInstanceCreateRequest.cloneInstanceCreationRequest();
        Map<String, String> allRequestParams = allRequestParams(uriInfo);
        DataResponse dataResponse = getQueryResponse(processInstanceQueryRequest, allRequestParams, uriInfo);
        if (log.isDebugEnabled()) {
            log.debug("ProcessInstanceCreation check:" + dataResponse.getSize());
        }
        int dataResponseSize = dataResponse.getSize();
        if (dataResponseSize > 0) {
            if (processInstanceCreateRequest.getCorrelate()) {
                if (dataResponseSize != 1) {
                    String responseMessage = "Correlation matching failed as there are more than one matching instance with " + "given variables state";
                    throw new NotFoundException(Response.ok().entity(responseMessage).status(Response.Status.NOT_FOUND).build());
                }
                if (processInstanceCreateRequest.getMessageName() == null) {
                    String responseMessage = "Correlation matching failed as messageName property is not specified";
                    throw new ActivitiIllegalArgumentException(responseMessage);
                }
                return performCorrelation(processInstanceCreateRequest);
            } else {
                dataResponse.setMessage("Instance information corresponding to the request");
                return Response.ok().entity(dataResponse).build();
            }
        }
    }
    RestResponseFactory restResponseFactory = new RestResponseFactory();
    Map<String, Object> startVariables = null;
    if (processInstanceCreateRequest.getVariables() != null) {
        startVariables = new HashMap<>();
        for (RestVariable variable : processInstanceCreateRequest.getVariables()) {
            if (variable.getName() == null) {
                throw new ActivitiIllegalArgumentException("Variable name is required.");
            }
            startVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable));
        }
    }
    // updated the additional variables
    if (processInstanceCreateRequest.getAdditionalVariables() != null) {
        if (startVariables == null) {
            startVariables = new HashMap<>();
        }
        for (RestVariable variable : processInstanceCreateRequest.getAdditionalVariables()) {
            if (variable.getName() == null) {
                throw new ActivitiIllegalArgumentException("Additional Variable name is required.");
            }
            startVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable));
        }
    }
    RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
    IdentityService identityService = BPMNOSGIService.getIdentityService();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String userName = carbonContext.getUsername();
    ProcessInstanceResponse processInstanceResponse;
    // Actually start the instance based on key or id
    try {
        ProcessInstance instance;
        identityService.setAuthenticatedUserId(userName);
        if (processInstanceCreateRequest.getProcessDefinitionId() != null) {
            instance = runtimeService.startProcessInstanceById(processInstanceCreateRequest.getProcessDefinitionId(), processInstanceCreateRequest.getBusinessKey(), startVariables);
        } else if (processInstanceCreateRequest.getProcessDefinitionKey() != null) {
            if (processInstanceCreateRequest.isCustomTenantSet()) {
                instance = runtimeService.startProcessInstanceByKeyAndTenantId(processInstanceCreateRequest.getProcessDefinitionKey(), processInstanceCreateRequest.getBusinessKey(), startVariables, processInstanceCreateRequest.getTenantId());
            } else {
                instance = runtimeService.startProcessInstanceByKey(processInstanceCreateRequest.getProcessDefinitionKey(), processInstanceCreateRequest.getBusinessKey(), startVariables);
            }
        } else {
            if (processInstanceCreateRequest.isCustomTenantSet()) {
                instance = runtimeService.startProcessInstanceByMessageAndTenantId(processInstanceCreateRequest.getMessage(), processInstanceCreateRequest.getBusinessKey(), startVariables, processInstanceCreateRequest.getTenantId());
            } else {
                instance = runtimeService.startProcessInstanceByMessage(processInstanceCreateRequest.getMessage(), processInstanceCreateRequest.getBusinessKey(), startVariables);
            }
        }
        HistoryService historyService = BPMNOSGIService.getHistoryService();
        if (processInstanceCreateRequest.getReturnVariables()) {
            Map<String, Object> runtimeVariableMap = null;
            List<HistoricVariableInstance> historicVariableList = null;
            if (instance.isEnded()) {
                historicVariableList = historyService.createHistoricVariableInstanceQuery().processInstanceId(instance.getId()).list();
            } else {
                runtimeVariableMap = runtimeService.getVariables(instance.getId());
            }
            processInstanceResponse = restResponseFactory.createProcessInstanceResponse(instance, true, runtimeVariableMap, historicVariableList, uriInfo.getBaseUri().toString());
        } else {
            processInstanceResponse = restResponseFactory.createProcessInstanceResponse(instance, uriInfo.getBaseUri().toString());
        }
    } catch (ActivitiObjectNotFoundException aonfe) {
        throw new ActivitiIllegalArgumentException(aonfe.getMessage(), aonfe);
    } finally {
        identityService.setAuthenticatedUserId(null);
    }
    return Response.ok().status(Response.Status.CREATED).entity(processInstanceResponse).build();
}
Also used : RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) RuntimeService(org.activiti.engine.RuntimeService) NotFoundException(javax.ws.rs.NotFoundException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) HistoryService(org.activiti.engine.HistoryService) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) ProcessInstanceQueryRequest(org.wso2.carbon.bpmn.rest.model.runtime.ProcessInstanceQueryRequest) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) IdentityService(org.activiti.engine.IdentityService) RestApiBasicAuthenticationException(org.wso2.carbon.bpmn.rest.common.exception.RestApiBasicAuthenticationException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) ProcessInstanceResponse(org.wso2.carbon.bpmn.rest.model.runtime.ProcessInstanceResponse) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) HistoricVariableInstance(org.activiti.engine.history.HistoricVariableInstance) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)28 RealmService (org.wso2.carbon.user.core.service.RealmService)15 CarbonContext (org.wso2.carbon.context.CarbonContext)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 UserRealm (org.wso2.carbon.user.core.UserRealm)6 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)6 ArrayList (java.util.ArrayList)5 Registry (org.wso2.carbon.registry.core.Registry)5 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 List (java.util.List)3 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)3 APIConstants (org.wso2.carbon.apimgt.impl.APIConstants)3 APIUtil (org.wso2.carbon.apimgt.impl.utils.APIUtil)3 ServiceReferenceHolder (org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder)3 RestApiConstants (org.wso2.carbon.apimgt.rest.api.common.RestApiConstants)3