Search in sources :

Example 21 with Tenant

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

the class BPSUserIdentityManager method getTenantIdFromUserId.

private int getTenantIdFromUserId(String userId) throws Exception {
    String[] userNameTokens = userId.split("@");
    int tenantId = BPMNConstants.SUPER_TENANT_ID;
    if (userNameTokens.length > 1) {
        TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(userNameTokens[userNameTokens.length - 1]);
        if (tenantInfoBean != null) {
            tenantId = tenantInfoBean.getTenantId();
        } else {
            throw new Exception("Error retrieving tenant id from userId :" + userId);
        }
    }
    return tenantId;
}
Also used : TenantInfoBean(org.wso2.carbon.stratos.common.beans.TenantInfoBean) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException)

Example 22 with Tenant

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

the class BPMNDeployer method init.

/**
 * Initializes the deployment per tenant
 *
 * @param configurationContext axis2 configurationContext
 */
@Override
public void init(ConfigurationContext configurationContext) {
    Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    log.info("Initializing BPMN Deployer for tenant " + tenantId + ".");
    try {
        File tenantRepoFolder = createTenantRepo(configurationContext);
        tenantRepository = BPMNServerHolder.getInstance().getTenantManager().createTenantRepository(tenantId);
        tenantRepository.setRepoFolder(tenantRepoFolder);
        // This is to check whether the user have added resolveDeploymentAtStartup system property to true if need
        // for resolving deployment to avoid inconsistencies
        boolean fixDeployments = true;
        if (System.getProperty(BPMNConstants.RESOLVE_DEPLOYMENT_SYS_PROP) != null && !Boolean.parseBoolean(System.getProperty(BPMNConstants.RESOLVE_DEPLOYMENT_SYS_PROP))) {
            fixDeployments = false;
            log.info("BPMN deployment inconsistencies will not resolved");
        }
        if (!isWorkerNode() && fixDeployments) {
            log.info("Resolving BPMN deployments to avoid inconsistencies");
            tenantRepository.fixDeployments();
        }
    } catch (BPSFault e) {
        String msg = "Tenant Error: " + tenantId;
        log.error(msg, e);
    }
}
Also used : BPSFault(org.wso2.carbon.bpmn.core.BPSFault) File(java.io.File)

Example 23 with Tenant

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

the class TenantRepository method undeploy.

/**
 * Undeploys a BPMN package.
 * This may be called by the BPMN deployer, when a BPMN package is deleted from the deployment folder or by admin services
 *
 * @param deploymentName package name to be undeployed
 * @param force          forceful deletion of package
 */
// public void undeploy(String deploymentName, boolean force) {
// 
// DeploymentMetaDataModel deploymentMetaDataModel;
// SqlSession sqlSession = null;
// try {
// // Remove the deployment from the tenant's registry
// deploymentMetaDataModel = activitiDAO
// .selectTenantAwareDeploymentModel(tenantId.toString(), deploymentName);
// 
// if ((deploymentMetaDataModel == null) && !force) {
// String msg = "Deployment: " + deploymentName + " does not exist.";
// log.warn(msg);
// return;
// }
// 
// ProcessEngineImpl engine = (ProcessEngineImpl) BPMNServerHolder.getInstance().getEngine();
// 
// DbSqlSessionFactory dbSqlSessionFactory =
// (DbSqlSessionFactory) engine.getProcessEngineConfiguration().
// getSessionFactories().get(DbSqlSession.class);
// 
// SqlSessionFactory sqlSessionFactory = dbSqlSessionFactory.getSqlSessionFactory();
// sqlSession = sqlSessionFactory.openSession();
// DeploymentMapper deploymentMapper = sqlSession.getMapper(DeploymentMapper.class);
// int rowCount = deploymentMapper.deleteDeploymentMetaData(deploymentMetaDataModel);
// 
// if (log.isDebugEnabled()) {
// log.debug("Total row count deleted=" + rowCount);
// }
// 
// // Remove the deployment archive from the tenant's deployment folder
// File deploymentArchive = new File(repoFolder, deploymentName + ".bar");
// FileUtils.deleteQuietly(deploymentArchive);
// 
// // Delete all versions of this package from the Activiti engine.
// RepositoryService repositoryService = engine.getRepositoryService();
// List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString()).
// deploymentName(deploymentName).list();
// for (Deployment deployment : deployments) {
// repositoryService.deleteDeployment(deployment.getId());
// }
// 
// //commit metadata
// sqlSession.commit();
// } finally {
// if (sqlSession != null) {
// sqlSession.close();
// }
// }
// 
// }
public void undeploy(String deploymentName, boolean force) throws BPSFault {
    try {
        // Remove the deployment from the tenant's registry
        RegistryService registryService = BPMNServerHolder.getInstance().getRegistryService();
        Registry tenantRegistry = registryService.getConfigSystemRegistry(tenantId);
        String deploymentRegistryPath = BPMNConstants.BPMN_REGISTRY_PATH + BPMNConstants.REGISTRY_PATH_SEPARATOR + deploymentName;
        if (!tenantRegistry.resourceExists(deploymentRegistryPath) && !force) {
            String msg = "Deployment: " + deploymentName + " does not exist.";
            log.warn(msg);
            return;
        }
        tenantRegistry.delete(deploymentRegistryPath);
        // Remove the deployment archive from the tenant's deployment folder
        File deploymentArchive = new File(repoFolder, deploymentName + ".bar");
        FileUtils.deleteQuietly(deploymentArchive);
        // Delete all versions of this package from the Activiti engine.
        ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
        RepositoryService repositoryService = engine.getRepositoryService();
        List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentTenantId(tenantId.toString()).deploymentName(deploymentName).list();
        for (Deployment deployment : deployments) {
            repositoryService.deleteDeployment(deployment.getId(), true);
        }
    } catch (RegistryException e) {
        String msg = "Failed to undeploy BPMN deployment: " + deploymentName + " for tenant: " + tenantId;
        log.error(msg, e);
        throw new BPSFault(msg, e);
    }
}
Also used : BPSFault(org.wso2.carbon.bpmn.core.BPSFault) Deployment(org.activiti.engine.repository.Deployment) Registry(org.wso2.carbon.registry.api.Registry) RegistryService(org.wso2.carbon.registry.api.RegistryService) File(java.io.File) RegistryException(org.wso2.carbon.registry.api.RegistryException) ProcessEngine(org.activiti.engine.ProcessEngine) RepositoryService(org.activiti.engine.RepositoryService)

Example 24 with Tenant

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

the class Axis2ConfigurationContextObserverImpl method terminatingConfigurationContext.

public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
    Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    log.info("Removing data publishers for this tenant " + tenantId + ".");
    TenantProcessStore tenantsProcessStore = bpelServer.getMultiTenantProcessStore().getTenantsProcessStore(tenantId);
    if (tenantsProcessStore != null) {
        Map dataPublisherMap = tenantsProcessStore.getDataPublisherMap();
        if (dataPublisherMap != null) {
            Collection<DataPublisher> dataPublisherCollection = dataPublisherMap.values();
            Iterator<DataPublisher> iterator = dataPublisherCollection.iterator();
            while (iterator.hasNext()) {
                DataPublisher dataPublisher = iterator.next();
                try {
                    dataPublisher.shutdown();
                } catch (DataEndpointException e) {
                    String errMsg = "Error while shutting down tenant Data Publisher";
                    log.error(errMsg, e);
                }
            }
            dataPublisherCollection.clear();
        }
    }
}
Also used : DataPublisher(org.wso2.carbon.databridge.agent.DataPublisher) DataEndpointException(org.wso2.carbon.databridge.agent.exception.DataEndpointException) TenantProcessStore(org.wso2.carbon.bpel.core.ode.integration.store.TenantProcessStore) Map(java.util.Map)

Example 25 with Tenant

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

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