use of org.apache.commons.lang3.StringUtils.isEmpty in project dhis2-core by dhis2.
the class TrackerBundleParamsConverter method convert.
/**
* Iterates over the collections of a dataBundle. If any objects in those
* collections have objects nested within them, they are extracted. For each
* object we process, we make sure all references are valid as well.
*
* @param dataBundle containing collections to check and update.
* @return a dataBundle with a flattened data structure, and valid uid
* references.
*/
@Override
public TrackerBundleParams convert(TrackerBundleParams dataBundle) {
Map<String, TrackedEntity> trackedEntityMap = new HashMap<>();
Map<String, Enrollment> enrollmentHashMap = new HashMap<>();
Map<String, Event> eventHashMap = new HashMap<>();
Map<String, Relationship> relationshipHashMap = new HashMap<>();
// Extract all enrollments and relationships, and set parent reference.
for (TrackedEntity te : dataBundle.getTrackedEntities()) {
updateTrackedEntityReferences(te);
trackedEntityMap.put(te.getTrackedEntity(), te);
extractEnrollments(te).forEach(enrollment -> enrollmentHashMap.put(enrollment.getEnrollment(), enrollment));
extractRelationships(te).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
}
// Set UID for all enrollments and notes
dataBundle.getEnrollments().stream().peek(enrollment -> updateEnrollmentReferences(enrollment, enrollment.getTrackedEntity())).forEach(enrollment -> enrollmentHashMap.put(enrollment.getEnrollment(), enrollment));
// Extract all events and relationships, and set parent references
for (Enrollment enrollment : enrollmentHashMap.values()) {
extractEvents(enrollment).forEach(event -> eventHashMap.put(event.getEvent(), event));
extractRelationships(enrollment).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
enrollment.setNotes(enrollment.getNotes().stream().filter(note -> !StringUtils.isEmpty(note.getValue())).peek(this::updateNoteReferences).collect(Collectors.toList()));
}
// Set UID for all events and notes
dataBundle.getEvents().stream().peek(event -> updateEventReferences(event, event.getEnrollment())).forEach(event -> eventHashMap.put(event.getEvent(), event));
// Extract all relationships
for (Event event : eventHashMap.values()) {
extractRelationships(event).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
event.setNotes(event.getNotes().stream().filter(note -> !StringUtils.isEmpty(note.getValue())).peek(this::updateNoteReferences).collect(Collectors.toList()));
}
// Set UID for all relationships
dataBundle.getRelationships().stream().peek(this::updateRelationshipReferences).forEach(relationship -> relationshipHashMap.put(relationship.getRelationship(), relationship));
return TrackerBundleParams.builder().trackedEntities(new ArrayList<>(trackedEntityMap.values())).enrollments(new ArrayList<>(enrollmentHashMap.values())).events(new ArrayList<>(eventHashMap.values())).relationships(new ArrayList<>(relationshipHashMap.values())).build();
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project jmeter by apache.
the class CustomGraphConsumer method createGroupInfos.
/*
* (non-Javadoc)
*
* @see org.apache.jmeter.report.csv.processor.impl.AbstractGraphConsumer#
* createGroupInfos()
*/
@Override
protected Map<String, GroupInfo> createGroupInfos() {
AbstractSeriesSelector seriesSelector = new AbstractSeriesSelector() {
@Override
public Iterable<String> select(Sample sample) {
return Collections.singletonList(sampleVariableName);
}
};
GraphValueSelector graphValueSelector = (series, sample) -> {
String value;
if (isNativeSampleVariableName) {
value = sample.getData(sampleVariableName);
} else {
value = sample.getData(CSVSaveService.VARIABLE_NAME_QUOTE_CHAR + sampleVariableName + CSVSaveService.VARIABLE_NAME_QUOTE_CHAR);
}
if (StringUtils.isEmpty(value) || "null".equals(value)) {
return null;
}
try {
return Converters.convert(Double.class, value);
} catch (ConvertException e) {
throw new IllegalArgumentException("Double converter failed", e);
}
};
return Collections.singletonMap(AbstractGraphConsumer.DEFAULT_GROUP, new GroupInfo(new MeanAggregatorFactory(), seriesSelector, // We ignore Transaction Controller results
graphValueSelector, false, false));
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project jmeter by apache.
the class RandomDate method execute.
/**
* {@inheritDoc}
*/
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
DateTimeFormatter formatter;
if (values.length > 3) {
String localeAsString = values[3].execute().trim();
if (!localeAsString.trim().isEmpty()) {
locale = LocaleUtils.toLocale(localeAsString);
}
}
String format = values[0].execute().trim();
if (!StringUtils.isEmpty(format)) {
try {
LocaleFormatObject lfo = new LocaleFormatObject(format, locale);
formatter = dateRandomFormatterCache.get(lfo, key -> createFormatter((LocaleFormatObject) key));
} catch (IllegalArgumentException ex) {
log.error("Format date pattern '{}' is invalid (see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)", format, // $NON-NLS-1$
ex);
return "";
}
} else {
try {
LocaleFormatObject lfo = new LocaleFormatObject("yyyy-MM-dd", locale);
formatter = dateRandomFormatterCache.get(lfo, key -> createFormatter((LocaleFormatObject) key));
} catch (IllegalArgumentException ex) {
log.error("Format date pattern '{}' is invalid (see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)", format, // $NON-NLS-1$
ex);
return "";
}
}
String dateStart = values[1].execute().trim();
long localStartDate = 0;
if (!dateStart.isEmpty()) {
try {
localStartDate = LocalDate.parse(dateStart, formatter).toEpochDay();
} catch (DateTimeParseException | NumberFormatException ex) {
// $NON-NLS-1$
log.error("Failed to parse Start Date '{}'", dateStart, ex);
}
} else {
try {
localStartDate = LocalDate.now(systemDefaultZoneID).toEpochDay();
} catch (DateTimeParseException | NumberFormatException ex) {
// $NON-NLS-1$
log.error("Failed to create current date '{}'", dateStart, ex);
}
}
long localEndDate = 0;
String dateEnd = values[2].execute().trim();
try {
localEndDate = LocalDate.parse(dateEnd, formatter).toEpochDay();
} catch (DateTimeParseException | NumberFormatException ex) {
// $NON-NLS-1$
log.error("Failed to parse End date '{}'", dateEnd, ex);
}
// Generate the random date
String dateString = "";
if (localEndDate < localStartDate) {
// $NON-NLS-1$
log.error("End Date '{}' must be greater than Start Date '{}'", dateEnd, dateStart);
} else {
long randomDay = ThreadLocalRandom.current().nextLong(localStartDate, localEndDate);
try {
dateString = LocalDate.ofEpochDay(randomDay).format(formatter);
} catch (DateTimeParseException | NumberFormatException ex) {
// $NON-NLS-1$
log.error("Failed to generate random date '{}'", randomDay, ex);
}
addVariableValue(dateString, values, 4);
}
return dateString;
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class Utils method getWrappedImageResourceWithInheritance.
/**
* Wraps an image resource with the properties and child resources of the inherited featured image of either
* the linked page or the page containing the resource.
*
* @param resource The image resource
* @param linkHandler The link handler
* @param currentStyle The style of the image resource
* @param currentPage The page containing the image resource
* @return The wrapped image resource augmented with inherited properties and child resource if inheritance is enabled, the plain image resource otherwise.
*/
public static Resource getWrappedImageResourceWithInheritance(Resource resource, LinkHandler linkHandler, Style currentStyle, Page currentPage) {
if (resource == null) {
LOGGER.error("The resource is not defined");
return null;
}
if (linkHandler == null) {
LOGGER.error("The link handler is not defined");
return null;
}
ValueMap properties = resource.getValueMap();
String fileReference = properties.get(DownloadResource.PN_REFERENCE, String.class);
Resource fileResource = resource.getChild(DownloadResource.NN_FILE);
boolean imageFromPageImage = properties.get(PN_IMAGE_FROM_PAGE_IMAGE, StringUtils.isEmpty(fileReference) && fileResource == null);
boolean altValueFromPageImage = properties.get(PN_ALT_VALUE_FROM_PAGE_IMAGE, imageFromPageImage);
if (imageFromPageImage) {
Resource inheritedResource = null;
String linkURL = properties.get(ImageResource.PN_LINK_URL, String.class);
boolean actionsEnabled = (currentStyle != null) ? !currentStyle.get(Teaser.PN_ACTIONS_DISABLED, !properties.get(Teaser.PN_ACTIONS_ENABLED, true)) : properties.get(Teaser.PN_ACTIONS_ENABLED, true);
Resource firstAction = Optional.of(resource).map(res -> res.getChild(Teaser.NN_ACTIONS)).map(actions -> actions.getChildren().iterator().next()).orElse(null);
if (StringUtils.isNotEmpty(linkURL)) {
// the inherited resource is the featured image of the linked page
Optional<Link> link = linkHandler.getLink(resource);
inheritedResource = link.map(link1 -> (Page) link1.getReference()).map(ComponentUtils::getFeaturedImage).orElse(null);
} else if (actionsEnabled && firstAction != null) {
// the inherited resource is the featured image of the first action's page (the resource is assumed to be a teaser)
inheritedResource = Optional.of(linkHandler.getLink(firstAction, Teaser.PN_ACTION_LINK)).map(link1 -> {
if (link1.isPresent()) {
Page linkedPage = (Page) link1.get().getReference();
return Optional.ofNullable(linkedPage).map(ComponentUtils::getFeaturedImage).orElse(null);
}
return null;
}).orElse(null);
} else {
// the inherited resource is the featured image of the current page
inheritedResource = Optional.ofNullable(currentPage).map(page -> {
Template template = page.getTemplate();
// make sure the resource is part of the currentPage or of its template
if (StringUtils.startsWith(resource.getPath(), currentPage.getPath()) || (template != null && StringUtils.startsWith(resource.getPath(), template.getPath()))) {
return ComponentUtils.getFeaturedImage(currentPage);
}
return null;
}).orElse(null);
}
Map<String, String> overriddenProperties = new HashMap<>();
Map<String, Resource> overriddenChildren = new HashMap<>();
String inheritedFileReference = null;
Resource inheritedFileResource = null;
String inheritedAlt = null;
String inheritedAltValueFromDAM = null;
if (inheritedResource != null) {
// Define the inherited properties
ValueMap inheritedProperties = inheritedResource.getValueMap();
inheritedFileReference = inheritedProperties.get(DownloadResource.PN_REFERENCE, String.class);
inheritedFileResource = inheritedResource.getChild(DownloadResource.NN_FILE);
inheritedAlt = inheritedProperties.get(ImageResource.PN_ALT, String.class);
inheritedAltValueFromDAM = inheritedProperties.get(PN_ALT_VALUE_FROM_DAM, String.class);
}
overriddenProperties.put(DownloadResource.PN_REFERENCE, inheritedFileReference);
overriddenChildren.put(DownloadResource.NN_FILE, inheritedFileResource);
// don't inherit the image title from the page image
overriddenProperties.put(PN_TITLE_VALUE_FROM_DAM, "false");
if (altValueFromPageImage) {
overriddenProperties.put(ImageResource.PN_ALT, inheritedAlt);
overriddenProperties.put(PN_ALT_VALUE_FROM_DAM, inheritedAltValueFromDAM);
} else {
overriddenProperties.put(PN_ALT_VALUE_FROM_DAM, "false");
}
return new CoreResourceWrapper(resource, resource.getResourceType(), null, overriddenProperties, overriddenChildren);
}
return resource;
}
use of org.apache.commons.lang3.StringUtils.isEmpty in project engine by craftercms.
the class ContentTypeBasedDataFetcher method processSelection.
/**
* Adds the required filters to the ES query for the given field
*/
protected void processSelection(String path, Selection currentSelection, BoolQueryBuilder query, List<String> queryFieldIncludes, DataFetchingEnvironment env) {
if (currentSelection instanceof Field) {
// If the current selection is a field
Field currentField = (Field) currentSelection;
// Get the original field name
String propertyName = getOriginalName(currentField.getName());
// Build the ES-friendly path
String fullPath = StringUtils.isEmpty(path) ? propertyName : path + "." + propertyName;
// If the field has sub selection
if (Objects.nonNull(currentField.getSelectionSet())) {
// If the field is a flattened component
if (fullPath.matches(COMPONENT_INCLUDE_REGEX)) {
// Include the 'content-type' field to make sure the type can be resolved during runtime
String contentTypeFieldPath = fullPath + "." + QUERY_FIELD_NAME_CONTENT_TYPE;
if (!queryFieldIncludes.contains(contentTypeFieldPath)) {
queryFieldIncludes.add(contentTypeFieldPath);
}
}
// Process recursively and finish
currentField.getSelectionSet().getSelections().forEach(selection -> processSelection(fullPath, selection, query, queryFieldIncludes, env));
return;
}
// Add the field to the list
logger.debug("Adding selected field '{}' to query", fullPath);
queryFieldIncludes.add(fullPath);
// Check the filters to build the ES query
Optional<Argument> arg = currentField.getArguments().stream().filter(a -> a.getName().equals(FILTER_NAME)).findFirst();
if (arg.isPresent()) {
logger.debug("Adding filters for field {}", fullPath);
Value<?> argValue = arg.get().getValue();
if (argValue instanceof ObjectValue) {
List<ObjectField> filters = ((ObjectValue) argValue).getObjectFields();
filters.forEach((filter) -> addFieldFilterFromObjectField(fullPath, filter, query, env));
} else if (argValue instanceof VariableReference && env.getVariables().containsKey(((VariableReference) argValue).getName())) {
Map<String, Object> map = (Map<String, Object>) env.getVariables().get(((VariableReference) argValue).getName());
map.entrySet().forEach(filter -> addFieldFilterFromMapEntry(fullPath, filter, query, env));
}
}
} else if (currentSelection instanceof InlineFragment) {
// If the current selection is an inline fragment, process recursively
InlineFragment fragment = (InlineFragment) currentSelection;
fragment.getSelectionSet().getSelections().forEach(selection -> processSelection(path, selection, query, queryFieldIncludes, env));
} else if (currentSelection instanceof FragmentSpread) {
// If the current selection is a fragment spread, find the fragment and process recursively
FragmentSpread fragmentSpread = (FragmentSpread) currentSelection;
FragmentDefinition fragmentDefinition = env.getFragmentsByName().get(fragmentSpread.getName());
fragmentDefinition.getSelectionSet().getSelections().forEach(selection -> processSelection(path, selection, query, queryFieldIncludes, env));
}
}
Aggregations