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();
}
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();
}
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;
}
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;
}
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);
}
}
Aggregations