use of org.apache.commons.lang3.StringUtils.isEmpty in project blueocean-plugin by jenkinsci.
the class PipelineNodeTest method sequentialParallelStagesLongRun.
@Ignore("Fails on ci.jenkins.io but not locally. Reasons unclear. Likely a timing issue.")
@Test
public void sequentialParallelStagesLongRun() throws Exception {
WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), "sequential_parallel_stages_long_run_time.jenkinsfile");
Slave s = j.createOnlineSlave();
s.setNumExecutors(3);
WorkflowRun run = p.scheduleBuild2(0).waitForStart();
j.waitForCompletion(run);
List<String> watchedStages = Arrays.asList("first-sequential-stage", "second-sequential-stage", "third-sequential-stage");
run = p.scheduleBuild2(0).waitForStart();
Thread.sleep(1000);
long loopCount = 0;
while (run.isBuilding()) {
PipelineNodeContainerImpl pipelineNodeContainer = new PipelineNodeContainerImpl(run, new Link("foo"));
List<BluePipelineNode> nodes = pipelineNodeContainer.getNodes();
for (BluePipelineNode node : nodes) {
if (StringUtils.isEmpty(node.getFirstParent()) && watchedStages.contains(node.getDisplayName())) {
LOGGER.error("node {} has getFirstParent null", node);
fail("node with getFirstParent null:" + node);
}
// we try to find edges with id for a non existing node in the list
List<BluePipelineNode.Edge> emptyEdges = node.getEdges().stream().filter(edge -> !nodes.stream().filter(bluePipelineNode -> bluePipelineNode.getId().equals(edge.getId())).findFirst().isPresent()).collect(Collectors.toList());
if (!emptyEdges.isEmpty()) {
// TODO remove this weird if but it's only to have breakpoint in IDE
assertTrue("edges with unknown nodes" + nodes, !emptyEdges.isEmpty());
}
}
LOGGER.debug("nodes size {}", nodes.size());
if (nodes.size() != 9) {
LOGGER.info("loop: " + loopCount + ", nodes size {}", nodes.size());
LOGGER.info("nodes != 9 {}", nodes);
fail("nodes != 9: " + nodes);
}
Thread.sleep(100);
}
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project CzechIdMng by bcvsolutions.
the class AbstractRoleParametrizationFormDefaultValueGenerator method getDefaultValuesByRoleDefinition.
protected IdmFormInstanceDto getDefaultValuesByRoleDefinition(IdmRoleDto roleDto, IdmGenerateValueDto valueGenerator, IdmFormInstanceDto existingEavs, DTO dto) {
UUID formDefinitionId = roleDto.getIdentityRoleAttributeDefinition();
// If form definition doesn't exist continue as normal
if (formDefinitionId == null) {
return null;
}
IdmFormDefinitionDto definition = roleService.getFormAttributeSubdefinition(roleDto);
// Internal behavior #getValuesFromInstances wants default form value
List<IdmFormValueDto> values = new ArrayList<>();
for (IdmFormAttributeDto attribute : definition.getFormAttributes()) {
String defaultValue = getDefaultValue(attribute, roleDto);
// check if exists default values
if (StringUtils.isEmpty(defaultValue)) {
// Check given values
List<IdmFormValueDto> existingValues = existingEavs == null ? null : //
existingEavs.getValues().stream().filter(existingEav -> {
//
return existingEav.getFormAttribute().equals(attribute.getId());
}).collect(//
Collectors.toList());
if (existingValues != null && !existingValues.isEmpty()) {
// Given value exist and default value doesn't exist
values.addAll(existingValues);
}
continue;
}
if (valueGenerator.isRegenerateValue()) {
// For regenerate just create values by default values
String regex = this.getRegex(valueGenerator);
String[] defaultValues = defaultValue.split(regex);
for (String defValue : defaultValues) {
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(defValue);
values.add(value);
}
} else {
if (existingEavs != null) {
// With check existing values
List<IdmFormValueDto> existingValues = existingEavs.getValues().stream().filter(existingVal -> {
//
return existingVal.getFormAttribute().equals(attribute.getId());
}).collect(//
Collectors.toList());
if (!existingValues.isEmpty()) {
// If existing value isn't empty use it (given values)
existingValues.forEach(existingValue -> {
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(existingValue.getValue(attribute.getPersistentType()));
values.add(value);
});
continue;
}
}
// If given values is empty use default
if (attribute.isMultiple()) {
// Default value may be multiple, just iterate over value splited by regex
String regex = this.getRegex(valueGenerator);
String[] defaultValues = defaultValue.split(regex);
for (String defValue : defaultValues) {
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(defValue);
values.add(value);
}
} else {
// If is value single valued use it as is it
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(defaultValue);
values.add(value);
}
}
}
return new IdmFormInstanceDto(dto, definition, values);
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project carbon-apimgt by wso2.
the class APIConsumerImpl method removeApplication.
/**
* Function to remove an Application from the API Store
*
* @param application - The Application Object that represents the Application
* @param username
* @throws APIManagementException
*/
@Override
public void removeApplication(Application application, String username) throws APIManagementException {
String uuid = application.getUUID();
Map<String, Pair<String, String>> consumerKeysOfApplication = null;
if (application.getId() == 0 && !StringUtils.isEmpty(uuid)) {
application = apiMgtDAO.getApplicationByUUID(uuid);
}
consumerKeysOfApplication = apiMgtDAO.getConsumerKeysForApplication(application.getId());
boolean isTenantFlowStarted = false;
int applicationId = application.getId();
boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
boolean isUserAppOwner;
if (isCaseInsensitiveComparisons) {
isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(username);
} else {
isUserAppOwner = application.getSubscriber().getName().equals(username);
}
if (!isUserAppOwner) {
throw new APIManagementException("user: " + username + ", " + "attempted to remove application owned by: " + application.getSubscriber().getName());
}
try {
String workflowExtRef;
ApplicationWorkflowDTO workflowDTO;
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
WorkflowExecutor createApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
WorkflowExecutor createProductionRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
WorkflowExecutor createSandboxRegistrationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
WorkflowExecutor removeApplicationWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceByApplicationID(application.getId());
// in a normal flow workflowExtRef is null when workflows are not enabled
if (workflowExtRef == null) {
workflowDTO = new ApplicationWorkflowDTO();
} else {
workflowDTO = (ApplicationWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
}
workflowDTO.setApplication(application);
workflowDTO.setCallbackUrl(removeApplicationWFExecutor.getCallbackURL());
workflowDTO.setUserName(this.username);
workflowDTO.setTenantDomain(tenantDomain);
workflowDTO.setTenantId(tenantId);
// clean up pending subscription tasks
Set<Integer> pendingSubscriptions = apiMgtDAO.getPendingSubscriptionsByApplicationId(applicationId);
for (int subscription : pendingSubscriptions) {
try {
workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(subscription);
createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
} catch (APIManagementException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to get external workflow reference for subscription " + subscription);
} catch (WorkflowException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to clean pending subscription approval task: " + subscription);
}
}
// cleanup pending application registration tasks
Map<String, String> keyManagerWiseProductionKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION);
Map<String, String> keyManagerWiseSandboxKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId, APIConstants.API_KEY_TYPE_SANDBOX);
keyManagerWiseProductionKeyStatus.forEach((keyManagerName, state) -> {
if (WorkflowStatus.CREATED.toString().equals(state)) {
try {
String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_PRODUCTION, keyManagerName);
createProductionRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
} catch (APIManagementException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to get external workflow reference for production key of application " + applicationId);
} catch (WorkflowException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to clean pending production key approval task of " + applicationId);
}
}
});
keyManagerWiseSandboxKeyStatus.forEach((keyManagerName, state) -> {
if (WorkflowStatus.CREATED.toString().equals(state)) {
try {
String applicationRegistrationExternalRef = apiMgtDAO.getRegistrationWFReference(applicationId, APIConstants.API_KEY_TYPE_SANDBOX, keyManagerName);
createSandboxRegistrationWFExecutor.cleanUpPendingTask(applicationRegistrationExternalRef);
} catch (APIManagementException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to get external workflow reference for sandbox key of application " + applicationId);
} catch (WorkflowException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to clean pending sandbox key approval task of " + applicationId);
}
}
});
if (workflowExtRef != null) {
try {
createApplicationWFExecutor.cleanUpPendingTask(workflowExtRef);
} catch (WorkflowException ex) {
// failed cleanup processes are ignored to prevent failing the application removal process
log.warn("Failed to clean pending application approval task of " + applicationId);
}
}
// update attributes of the new remove workflow to be created
workflowDTO.setStatus(WorkflowStatus.CREATED);
workflowDTO.setCreatedTime(System.currentTimeMillis());
workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
workflowDTO.setExternalWorkflowReference(removeApplicationWFExecutor.generateUUID());
removeApplicationWFExecutor.execute(workflowDTO);
JSONObject appLogObject = new JSONObject();
appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());
appLogObject.put(APIConstants.AuditLogConstants.GROUPS, application.getGroupId());
appLogObject.put(APIConstants.AuditLogConstants.OWNER, application.getSubscriber().getName());
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
} catch (WorkflowException e) {
String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION + " " + "for applicationID " + application.getId();
handleException(errorMsg, e);
} finally {
if (isTenantFlowStarted) {
endTenantFlow();
}
}
if (log.isDebugEnabled()) {
String logMessage = "Application Name: " + application.getName() + " successfully removed";
log.debug(logMessage);
}
// Extracting API details for the recommendation system
if (recommendationEnvironment != null) {
RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(applicationId, username, requestedTenant);
Thread recommendationThread = new Thread(extractor);
recommendationThread.start();
}
// get the workflow state once the executor is executed.
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(applicationId), WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
// wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
if (wfDTO != null) {
if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus()) || wfDTO.getStatus() == null) {
ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
}
} else {
ApplicationEvent applicationEvent = new ApplicationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_DELETE.name(), tenantId, application.getOrganization(), applicationId, application.getUUID(), application.getName(), application.getTokenType(), application.getTier(), application.getGroupId(), Collections.EMPTY_MAP, username);
APIUtil.sendNotification(applicationEvent, APIConstants.NotifierType.APPLICATION.name());
}
if (consumerKeysOfApplication != null && consumerKeysOfApplication.size() > 0) {
for (Map.Entry<String, Pair<String, String>> entry : consumerKeysOfApplication.entrySet()) {
String consumerKey = entry.getKey();
String keyManagerName = entry.getValue().getKey();
String keyManagerTenantDomain = entry.getValue().getValue();
ApplicationRegistrationEvent removeEntryTrigger = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.REMOVE_APPLICATION_KEYMAPPING.name(), APIUtil.getTenantIdFromTenantDomain(keyManagerTenantDomain), keyManagerTenantDomain, application.getId(), application.getUUID(), consumerKey, application.getKeyType(), keyManagerName);
APIUtil.sendNotification(removeEntryTrigger, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
}
}
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsGet.
/**
* Get all subscriptions that are of user or shared subscriptions of the user's group.
* <p/>
* If apiId is specified this will return the subscribed applications of that api
* If application id is specified this will return the api subscriptions of that application
*
* @param apiId api identifier
* @param applicationId application identifier
* @param offset starting index of the subscription list
* @param limit max num of subscriptions returned
* @param ifNoneMatch If-None-Match header value
* @return matched subscriptions as a list of SubscriptionDTOs
*/
@Override
public Response subscriptionsGet(String apiId, String applicationId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
Subscriber subscriber = new Subscriber(username);
Set<SubscribedAPI> subscriptions;
List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
// pre-processing
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
// currently groupId is taken from the user so that groupId coming as a query parameter is not honored.
// As a improvement, we can check admin privileges of the user and honor groupId.
groupId = RestApiUtil.getLoggedInUserGroupId();
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
SubscriptionListDTO subscriptionListDTO;
if (!StringUtils.isEmpty(apiId)) {
// todo : FIX properly, need to done properly with backend side pagination.
// todo : getSubscribedIdentifiers() method should NOT be used. Appears to be too slow.
// This will fail with an authorization failed exception if user does not have permission to access the API
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
if (apiTypeWrapper.isAPIProduct()) {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
} else {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
}
// sort by application name
subscribedAPIList.addAll(subscriptions);
subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
SubscriptionMappingUtil.setPaginationParams(subscriptionListDTO, apiId, "", limit, offset, subscribedAPIList.size());
return Response.ok().entity(subscriptionListDTO).build();
} else if (!StringUtils.isEmpty(applicationId)) {
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
return null;
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
subscriptions = apiConsumer.getPaginatedSubscribedAPIsByApplication(application, offset, limit, organization);
subscribedAPIList.addAll(subscriptions);
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
return Response.ok().entity(subscriptionListDTO).build();
} else {
// neither apiId nor applicationId is given
RestApiUtil.handleBadRequest("Either applicationId or apiId should be available", log);
return null;
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
} else if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
RestApiUtil.handleInternalServerError("Error while getting subscriptions of the user " + username, e, log);
}
}
return null;
}
Aggregations