Search in sources :

Example 16 with Tenant

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

the class PeopleActivity method invoke.

public String invoke(ExtensionContext extensionContext) throws FaultException {
    BPELMessageContext taskMessageContext = new BPELMessageContext(hiWSDL);
    UUID messageID = null;
    int tenantId = B4PServiceComponent.getBPELServer().getMultiTenantProcessStore().getTenantId(processId);
    String tenantDomain = null;
    try {
        tenantDomain = B4PContentHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
    } catch (UserStoreException e) {
        log.error(" Cannot find the tenant domain " + e.toString());
    }
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
    try {
        // Setting the attachment id attachmentIDList
        List<Long> attachmentIDList = extractAttachmentIDsToBeSentToHumanTask(extensionContext, taskMessageContext);
        taskMessageContext.setOperationName(getOperationName());
        SOAPHelper soapHelper = new SOAPHelper(getBinding(), getSoapFactory(), isRPC);
        MessageContext messageContext = new MessageContext();
        /*
            Adding attachment ID list as a method input to createSoapRequest makes no sense.
            Have to fix. Here we can't embed attachments in MessageContext, as we have only a
            list of attachment ids.
            */
        soapHelper.createSoapRequest(messageContext, (Element) extensionContext.readVariable(inputVarName), getOperation(extensionContext), attachmentIDList);
        // Coordination Context and skipable attribute is only valid for a Task.
        if (InteractionType.TASK.equals(activityType)) {
            // Note: If registration service is not enabled, we don't need to send coor-context.
            if (CoordinationConfiguration.getInstance().isHumantaskCoordinationEnabled() && CoordinationConfiguration.getInstance().isRegistrationServiceEnabled()) {
                messageID = UUID.randomUUID();
                soapHelper.addCoordinationContext(messageContext, messageID.toString(), getRegistrationServiceURL());
            }
            // Adding HumanTask Context overriding attributes.
            soapHelper.addOverridingHumanTaskAttributes(messageContext, isSkipable);
        }
        taskMessageContext.setInMessageContext(messageContext);
        taskMessageContext.setPort(getServicePort());
        taskMessageContext.setService(getServiceName());
        taskMessageContext.setRPCStyleOperation(isRPC);
        taskMessageContext.setTwoWay(isTwoWay);
        taskMessageContext.setSoapFactoryForCurrentMessageFlow(getSoapFactory());
        taskMessageContext.setWsdlBindingForCurrentMessageFlow(getBinding());
        taskMessageContext.setUep(getUnifiedEndpoint());
        taskMessageContext.setCaller(processId.getLocalPart());
        AxisServiceUtils.invokeService(taskMessageContext, getConfigurationContext());
    } catch (AxisFault axisFault) {
        log.error(axisFault, axisFault);
        throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Error occurred while invoking service " + serviceName, axisFault);
    } catch (B4PCoordinationException coordinationFault) {
        throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, "Error occurred while generating Registration Service URL" + serviceName, coordinationFault);
    }
    if (taskMessageContext.getFaultMessageContext() != null || taskMessageContext.getOutMessageContext().isFault()) {
        MessageContext faultContext = taskMessageContext.getFaultMessageContext() != null ? taskMessageContext.getFaultMessageContext() : taskMessageContext.getOutMessageContext();
        log.warn("SOAP Fault: " + faultContext.getEnvelope().toString());
        throw new FaultException(BPEL4PeopleConstants.B4P_FAULT, faultContext.getEnvelope().toString());
    }
    String taskID = SOAPHelper.parseResponseFeedback(taskMessageContext.getOutMessageContext().getEnvelope().getBody());
    // Ignore Notifications, since we are ignore coordination context for notification.
    if (CoordinationConfiguration.getInstance().isHumantaskCoordinationEnabled() && InteractionType.TASK.equals(activityType)) {
        Long instanceID = extensionContext.getProcessId();
        if (CoordinationConfiguration.getInstance().isRegistrationServiceEnabled()) {
            try {
                // Already coordinated with Registration service.
                updateCoordinationData(messageID.toString(), Long.toString(instanceID), taskID);
            } catch (Exception e) {
                log.error("Error occurred while updating humantask coordination data.", e);
            }
        } else {
            // Handler URL by manually.
            try {
                messageID = UUID.randomUUID();
                String protocolHandlerURL = generateTaskProtocolHandlerURL(taskMessageContext);
                if (log.isDebugEnabled()) {
                    log.debug("Generated Protocol Handler URL : " + protocolHandlerURL);
                }
                createCoordinationData(messageID.toString(), protocolHandlerURL, Long.toString(instanceID), taskID);
            } catch (Exception e) {
                log.error("Error occurred while creating humantask coordination data for coordinated task.", e);
            }
        }
    }
    return taskID;
}
Also used : AxisFault(org.apache.axis2.AxisFault) BPELMessageContext(org.wso2.carbon.bpel.core.ode.integration.BPELMessageContext) WSDL11Endpoint(org.apache.ode.bpel.epr.WSDL11Endpoint) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) FaultException(org.apache.ode.bpel.common.FaultException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) B4PCoordinationException(org.wso2.carbon.bpel.b4p.coordination.B4PCoordinationException) SocketException(java.net.SocketException) SOAPHelper(org.wso2.carbon.bpel.b4p.utils.SOAPHelper) FaultException(org.apache.ode.bpel.common.FaultException) B4PCoordinationException(org.wso2.carbon.bpel.b4p.coordination.B4PCoordinationException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) BPELMessageContext(org.wso2.carbon.bpel.core.ode.integration.BPELMessageContext) MessageContext(org.apache.axis2.context.MessageContext) UUID(java.util.UUID)

Example 17 with Tenant

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

the class BPELDeployer method init.

public void init(ConfigurationContext configurationContext) {
    Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    log.info("Initializing BPEL Deployer for tenant " + tenantId + ".");
    File bpelRepo = null;
    try {
        BPELDeployerServiceComponent.getTenantRegistryLoader().loadTenantRegistry(tenantId);
        bpelRepo = createBPELRepository(configurationContext);
    } catch (DeploymentException e) {
        log.warn("BPEL repository creation failed.", e);
    } catch (RegistryException e) {
        log.warn("Initialization of tenant process store failed for tenant: " + tenantId + " This can cause issues in deployment of BPEL packages.", e);
    }
    BPELServer bpsServer = BPELDeployerServiceComponent.getBPELServer();
    tenantProcessStore = bpsServer.getMultiTenantProcessStore().createProcessStoreForTenant(configurationContext);
    tenantProcessStore.setBpelArchiveRepo(bpelRepo);
    configurationContext.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, bpsServer.getHttpConnectionManager());
    try {
        tenantProcessStore.init();
    } catch (Exception re) {
        log.warn("Initialization of tenant process store failed for tenant: " + tenantId + " This can cause issues in deployment of BPEL packages.", re);
    }
}
Also used : DeploymentException(org.apache.axis2.deployment.DeploymentException) BPELServer(org.wso2.carbon.bpel.core.ode.integration.BPELServer) File(java.io.File) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) DeploymentException(org.apache.axis2.deployment.DeploymentException)

Example 18 with Tenant

use of org.wso2.carbon.user.api.Tenant 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 19 with Tenant

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

the class BPMNInstanceService method getTenantBPMNHistoryInstances.

/**
 * Get tenant history instances from a passed list
 *
 * @param instances
 * @return list of BPMNInstances
 */
private BPMNInstance[] getTenantBPMNHistoryInstances(List<ProcessInstance> instances) {
    BPMNInstance bpmnInstance;
    Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    List<BPMNInstance> bpmnInstances = new ArrayList<BPMNInstance>();
    RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
    HistoricProcessInstanceQuery query = BPMNServerHolder.getInstance().getEngine().getHistoryService().createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
    for (ProcessInstance instance : instances) {
        bpmnInstance = new BPMNInstance();
        bpmnInstance.setInstanceId(instance.getId());
        bpmnInstance.setProcessId(instance.getProcessDefinitionId());
        bpmnInstance.setSuspended(instance.isSuspended());
        bpmnInstance.setStartTime(query.processInstanceId(instance.getId()).singleResult().getStartTime());
        bpmnInstance.setVariables(formatVariables(runtimeService.getVariables(instance.getId())));
        bpmnInstances.add(bpmnInstance);
    }
    return bpmnInstances.toArray(new BPMNInstance[bpmnInstances.size()]);
}
Also used : BPMNInstance(org.wso2.carbon.bpmn.core.mgt.model.BPMNInstance) HistoricProcessInstanceQuery(org.activiti.engine.history.HistoricProcessInstanceQuery) RuntimeService(org.activiti.engine.RuntimeService) ArrayList(java.util.ArrayList) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ProcessInstance(org.activiti.engine.runtime.ProcessInstance)

Example 20 with Tenant

use of org.wso2.carbon.user.api.Tenant 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)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 UserStoreException (org.wso2.carbon.user.api.UserStoreException)88 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)83 ArrayList (java.util.ArrayList)79 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 PreparedStatement (java.sql.PreparedStatement)51 SQLException (java.sql.SQLException)50 IOException (java.io.IOException)49 Connection (java.sql.Connection)49 HashMap (java.util.HashMap)44 ResultSet (java.sql.ResultSet)43 JSONObject (org.json.simple.JSONObject)41 Resource (org.wso2.carbon.registry.core.Resource)40 Registry (org.wso2.carbon.registry.core.Registry)38 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)34 API (org.wso2.carbon.apimgt.api.model.API)34 Test (org.junit.Test)33 File (java.io.File)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)30