use of org.apache.commons.lang3.ObjectUtils.firstNonNull in project dhis2-core by dhis2.
the class TrackedEntityInstanceController method getTrackedEntityInstances.
// -------------------------------------------------------------------------
// READ
// -------------------------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public RootNode getTrackedEntityInstances(@RequestParam(required = false) String query, @RequestParam(required = false) Set<String> attribute, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) String ou, @RequestParam(required = false) OrganisationUnitSelectionMode ouMode, @RequestParam(required = false) String program, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) Boolean followUp, @RequestParam(required = false) Date lastUpdatedStartDate, @RequestParam(required = false) Date lastUpdatedEndDate, @RequestParam(required = false) Date programStartDate, @RequestParam(required = false) Date programEnrollmentStartDate, @RequestParam(required = false) Date programEndDate, @RequestParam(required = false) Date programEnrollmentEndDate, @RequestParam(required = false) Date programIncidentStartDate, @RequestParam(required = false) Date programIncidentEndDate, @RequestParam(required = false) String trackedEntity, @RequestParam(required = false) String trackedEntityInstance, @RequestParam(required = false) EventStatus eventStatus, @RequestParam(required = false) Date eventStartDate, @RequestParam(required = false) Date eventEndDate, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) boolean totalPages, @RequestParam(required = false) boolean skipPaging, @RequestParam(required = false) boolean includeDeleted, @RequestParam(required = false) String order) throws Exception {
programEnrollmentStartDate = ObjectUtils.firstNonNull(programEnrollmentStartDate, programStartDate);
programEnrollmentEndDate = ObjectUtils.firstNonNull(programEnrollmentEndDate, programEndDate);
List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
if (fields.isEmpty()) {
fields.add(":all");
}
Set<String> orgUnits = TextUtils.splitToArray(ou, TextUtils.SEMICOLON);
RootNode rootNode = NodeUtils.createMetadata();
List<TrackedEntityInstance> trackedEntityInstances;
TrackedEntityInstanceQueryParams queryParams = instanceService.getFromUrl(query, attribute, filter, orgUnits, ouMode, program, programStatus, followUp, lastUpdatedStartDate, lastUpdatedEndDate, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity, eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging, includeDeleted, getOrderParams(order));
if (trackedEntityInstance == null) {
trackedEntityInstances = trackedEntityInstanceService.getTrackedEntityInstances(queryParams, getTrackedEntityInstanceParams(fields));
} else {
Set<String> trackedEntityInstanceIds = TextUtils.splitToArray(trackedEntityInstance, TextUtils.SEMICOLON);
trackedEntityInstances = trackedEntityInstanceIds != null ? trackedEntityInstanceIds.stream().map(id -> trackedEntityInstanceService.getTrackedEntityInstance(id, getTrackedEntityInstanceParams(fields))).collect(Collectors.toList()) : null;
}
if (queryParams.isPaging() && queryParams.isTotalPages()) {
int count = trackedEntityInstanceService.getTrackedEntityInstanceCount(queryParams);
Pager pager = new Pager(queryParams.getPageWithDefault(), count, queryParams.getPageSizeWithDefault());
rootNode.addChild(NodeUtils.createPager(pager));
}
rootNode.addChild(fieldFilterService.filter(TrackedEntityInstance.class, trackedEntityInstances, fields));
return rootNode;
}
use of org.apache.commons.lang3.ObjectUtils.firstNonNull in project estatio by estatio.
the class LeaseTermForDeposit method calculateDepositBaseValue.
@Programmatic
BigDecimal calculateDepositBaseValue(final LocalDate verificationDate) {
BigDecimal calculatedValue = BigDecimal.ZERO;
for (LeaseItem leaseItem : this.getLeaseItem().getSourceItems().stream().map(i -> i.getSourceItem()).collect(Collectors.toList())) {
LocalDate dateToUse = ObjectUtils.firstNonNull(getFixedDepositCalculationDate(), verificationDate);
BigDecimal valueForDate = leaseItem.valueForDate(dateToUse);
calculatedValue = calculatedValue.add(addVatIfNeeded(valueForDate, leaseItem, dateToUse));
}
return calculatedValue;
}
use of org.apache.commons.lang3.ObjectUtils.firstNonNull in project alf.io by alfio-event.
the class TicketReservationManager method reserveTicketsForCategory.
void reserveTicketsForCategory(Event event, String reservationId, TicketReservationWithOptionalCodeModification ticketReservation, Locale locale, boolean forWaitingQueue, PromoCodeDiscount accessCodeOrDiscount, PromoCodeDiscount dynamicDiscount) {
List<SpecialPrice> specialPrices;
if (accessCodeOrDiscount != null && accessCodeOrDiscount.getCodeType() == CodeType.ACCESS && ticketReservation.getTicketCategoryId().equals(accessCodeOrDiscount.getHiddenCategoryId()) && Boolean.TRUE.equals(ticketCategoryRepository.isAccessRestricted(accessCodeOrDiscount.getHiddenCategoryId()))) {
specialPrices = reserveTokensForAccessCode(ticketReservation, accessCodeOrDiscount);
} else {
// first check if there is another pending special price token bound to the current sessionId
Optional<SpecialPrice> specialPrice = fixToken(ticketReservation.getSpecialPrice(), ticketReservation.getTicketCategoryId(), event.getId(), ticketReservation);
specialPrices = specialPrice.stream().collect(toList());
}
List<Integer> reservedForUpdate = reserveTickets(event.getId(), ticketReservation, forWaitingQueue ? asList(TicketStatus.RELEASED, TicketStatus.PRE_RESERVED) : singletonList(TicketStatus.FREE));
int requested = ticketReservation.getQuantity();
if (reservedForUpdate.size() != requested) {
throw new NotEnoughTicketsException();
}
TicketCategory category = ticketCategoryRepository.getByIdAndActive(ticketReservation.getTicketCategoryId(), event.getId());
List<Map<String, String>> ticketMetadata = requireNonNullElse(ticketReservation.getMetadata(), List.of());
if (!specialPrices.isEmpty()) {
if (specialPrices.size() != reservedForUpdate.size()) {
throw new NotEnoughTicketsException();
}
AtomicInteger counter = new AtomicInteger(0);
var ticketsAndSpecialPrices = specialPrices.stream().map(sp -> {
int index = counter.getAndIncrement();
return Triple.of(reservedForUpdate.get(index), sp, getAtIndexOrNull(ticketMetadata, index));
}).collect(Collectors.toList());
if (specialPrices.size() == 1) {
var ticketId = reservedForUpdate.get(0);
var sp = specialPrices.get(0);
var accessCodeId = accessCodeOrDiscount != null && accessCodeOrDiscount.getHiddenCategoryId() != null ? accessCodeOrDiscount.getId() : null;
TicketMetadata metadata = null;
var attributes = getAtIndexOrNull(ticketMetadata, 0);
if (attributes != null) {
metadata = new TicketMetadata(null, null, attributes);
}
ticketRepository.reserveTicket(reservationId, ticketId, sp.getId(), locale.getLanguage(), category.getSrcPriceCts(), category.getCurrencyCode(), event.getVatStatus(), TicketMetadataContainer.fromMetadata(metadata));
specialPriceRepository.updateStatus(sp.getId(), Status.PENDING.toString(), null, accessCodeId);
} else {
jdbcTemplate.batchUpdate(ticketRepository.batchReserveTicketsForSpecialPrice(), ticketsAndSpecialPrices.stream().map(triple -> {
TicketMetadataContainer metadata = null;
if (triple.getRight() != null) {
metadata = TicketMetadataContainer.fromMetadata(new TicketMetadata(null, null, triple.getRight()));
}
return new MapSqlParameterSource(RESERVATION_ID, reservationId).addValue("ticketId", triple.getLeft()).addValue("specialCodeId", triple.getMiddle().getId()).addValue("userLanguage", locale.getLanguage()).addValue("srcPriceCts", category.getSrcPriceCts()).addValue("currencyCode", category.getCurrencyCode()).addValue("ticketMetadata", json.asJsonString(metadata)).addValue("vatStatus", event.getVatStatus().toString());
}).toArray(MapSqlParameterSource[]::new));
specialPriceRepository.batchUpdateStatus(specialPrices.stream().map(SpecialPrice::getId).collect(toList()), Status.PENDING, Objects.requireNonNull(accessCodeOrDiscount).getId());
}
} else {
int reserved = ticketRepository.reserveTickets(reservationId, reservedForUpdate, category, locale.getLanguage(), event.getVatStatus(), idx -> {
var metadata = getAtIndexOrNull(ticketMetadata, idx);
if (metadata != null) {
return json.asJsonString(TicketMetadataContainer.fromMetadata(new TicketMetadata(null, null, metadata)));
}
return null;
});
Validate.isTrue(reserved == reservedForUpdate.size(), "Cannot reserve all tickets");
}
Ticket ticket = ticketRepository.findById(reservedForUpdate.get(0), category.getId());
var discountToApply = ObjectUtils.firstNonNull(dynamicDiscount, accessCodeOrDiscount);
TicketPriceContainer priceContainer = TicketPriceContainer.from(ticket, null, event.getVat(), event.getVatStatus(), discountToApply);
var currencyCode = priceContainer.getCurrencyCode();
ticketRepository.updateTicketPrice(reservedForUpdate, category.getId(), event.getId(), category.getSrcPriceCts(), MonetaryUtil.unitToCents(priceContainer.getFinalPrice(), currencyCode), MonetaryUtil.unitToCents(priceContainer.getVAT(), currencyCode), MonetaryUtil.unitToCents(priceContainer.getAppliedDiscount(), currencyCode), category.getCurrencyCode(), priceContainer.getVatStatus());
}
use of org.apache.commons.lang3.ObjectUtils.firstNonNull in project dhis2-core by dhis2.
the class JdbcEventStore method getEvents.
// -------------------------------------------------------------------------
// EventStore implementation
// -------------------------------------------------------------------------
@Override
public List<Event> getEvents(EventSearchParams params, List<OrganisationUnit> organisationUnits, Map<String, Set<String>> psdesWithSkipSyncTrue) {
User user = currentUserService.getCurrentUser();
setAccessiblePrograms(user, params);
Map<String, Event> eventUidToEventMap = new HashMap<>(params.getPageSizeWithDefault());
List<Event> events = new ArrayList<>();
List<Long> relationshipIds = new ArrayList<>();
final Gson gson = new Gson();
String sql = buildSql(params, organisationUnits, user);
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql);
log.debug("Event query SQL: " + sql);
Set<String> notes = new HashSet<>();
while (rowSet.next()) {
if (rowSet.getString("psi_uid") == null || (params.getCategoryOptionCombo() == null && !isSuper(user) && !userHasAccess(rowSet))) {
continue;
}
String psiUid = rowSet.getString("psi_uid");
Event event;
if (!eventUidToEventMap.containsKey(psiUid)) {
validateIdentifiersPresence(rowSet, params.getIdSchemes(), true);
event = new Event();
eventUidToEventMap.put(psiUid, event);
if (!params.isSkipEventId()) {
event.setUid(psiUid);
event.setEvent(psiUid);
}
event.setTrackedEntityInstance(rowSet.getString("tei_uid"));
event.setStatus(EventStatus.valueOf(rowSet.getString("psi_status")));
ProgramType programType = ProgramType.fromValue(rowSet.getString("p_type"));
event.setProgram(rowSet.getString("p_identifier"));
event.setProgramType(programType);
event.setProgramStage(rowSet.getString("ps_identifier"));
event.setOrgUnit(rowSet.getString("ou_identifier"));
event.setDeleted(rowSet.getBoolean("psi_deleted"));
if (programType != ProgramType.WITHOUT_REGISTRATION) {
event.setEnrollment(rowSet.getString("pi_uid"));
event.setEnrollmentStatus(EnrollmentStatus.fromProgramStatus(ProgramStatus.valueOf(rowSet.getString("pi_status"))));
event.setFollowup(rowSet.getBoolean("pi_followup"));
}
if (params.getCategoryOptionCombo() == null && !isSuper(user)) {
event.setOptionSize(rowSet.getInt("option_size"));
}
event.setAttributeOptionCombo(rowSet.getString("coc_identifier"));
event.setAttributeCategoryOptions(rowSet.getString("deco_uid"));
event.setTrackedEntityInstance(rowSet.getString("tei_uid"));
event.setStoredBy(rowSet.getString("psi_storedby"));
event.setOrgUnitName(rowSet.getString("ou_name"));
event.setDueDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_duedate")));
event.setEventDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_executiondate")));
event.setCreated(DateUtils.getIso8601NoTz(rowSet.getDate("psi_created")));
event.setCreatedByUserInfo(jsonToUserInfo(rowSet.getString("psi_createdbyuserinfo"), jsonMapper));
event.setLastUpdated(DateUtils.getIso8601NoTz(rowSet.getDate("psi_lastupdated")));
event.setLastUpdatedByUserInfo(jsonToUserInfo(rowSet.getString("psi_lastupdatedbyuserinfo"), jsonMapper));
event.setCompletedBy(rowSet.getString("psi_completedby"));
event.setCompletedDate(DateUtils.getIso8601NoTz(rowSet.getDate("psi_completeddate")));
if (rowSet.getObject("psi_geometry") != null) {
try {
Geometry geom = new WKTReader().read(rowSet.getString("psi_geometry"));
event.setGeometry(geom);
} catch (ParseException e) {
log.error("Unable to read geometry for event '" + event.getUid() + "': ", e);
}
}
if (rowSet.getObject("user_assigned") != null) {
event.setAssignedUser(rowSet.getString("user_assigned"));
event.setAssignedUserUsername(rowSet.getString("user_assigned_username"));
event.setAssignedUserDisplayName(rowSet.getString("user_assigned_name"));
}
events.add(event);
} else {
event = eventUidToEventMap.get(psiUid);
String attributeCategoryCombination = event.getAttributeCategoryOptions();
String currentAttributeCategoryCombination = rowSet.getString("deco_uid");
if (!attributeCategoryCombination.contains(currentAttributeCategoryCombination)) {
event.setAttributeCategoryOptions(attributeCategoryCombination + ";" + currentAttributeCategoryCombination);
}
}
if (!StringUtils.isEmpty(rowSet.getString("psi_eventdatavalues"))) {
Set<EventDataValue> eventDataValues = convertEventDataValueJsonIntoSet(rowSet.getString("psi_eventdatavalues"));
for (EventDataValue dv : eventDataValues) {
DataValue dataValue = convertEventDataValueIntoDtoDataValue(dv);
if (params.isSynchronizationQuery()) {
if (psdesWithSkipSyncTrue.containsKey(rowSet.getString("ps_uid")) && psdesWithSkipSyncTrue.get(rowSet.getString("ps_uid")).contains(dv.getDataElement())) {
dataValue.setSkipSynchronization(true);
} else {
dataValue.setSkipSynchronization(false);
}
}
event.getDataValues().add(dataValue);
}
}
if (rowSet.getString("psinote_value") != null && !notes.contains(rowSet.getString("psinote_id"))) {
Note note = new Note();
note.setNote(rowSet.getString("psinote_uid"));
note.setValue(rowSet.getString("psinote_value"));
note.setStoredDate(DateUtils.getIso8601NoTz(rowSet.getDate("psinote_storeddate")));
note.setStoredBy(rowSet.getString("psinote_storedby"));
if (rowSet.getObject("usernote_id") != null) {
note.setLastUpdatedBy(UserInfoSnapshot.of(rowSet.getLong("usernote_id"), rowSet.getString("usernote_code"), rowSet.getString("usernote_uid"), rowSet.getString("usernote_username"), rowSet.getString("userinfo_firstname"), rowSet.getString("userinfo_surname")));
}
note.setLastUpdated(rowSet.getDate("psinote_lastupdated"));
event.getNotes().add(note);
notes.add(rowSet.getString("psinote_id"));
}
if (params.isIncludeRelationships() && rowSet.getObject("psi_rl") != null) {
PGobject pGobject = (PGobject) rowSet.getObject("psi_rl");
if (pGobject != null) {
String value = pGobject.getValue();
relationshipIds.addAll(Lists.newArrayList(gson.fromJson(value, Long[].class)));
}
}
}
final Multimap<String, Relationship> map = eventStore.getRelationshipsByIds(relationshipIds);
if (!map.isEmpty()) {
events.forEach(e -> e.getRelationships().addAll(map.get(e.getEvent())));
}
IdSchemes idSchemes = ObjectUtils.firstNonNull(params.getIdSchemes(), new IdSchemes());
IdScheme dataElementIdScheme = idSchemes.getDataElementIdScheme();
if (dataElementIdScheme != IdScheme.ID && dataElementIdScheme != IdScheme.UID) {
CachingMap<String, String> dataElementUidToIdentifierCache = new CachingMap<>();
List<Collection<DataValue>> dataValuesList = events.stream().map(Event::getDataValues).collect(Collectors.toList());
populateCache(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
convertDataValuesIdentifiers(dataElementIdScheme, dataValuesList, dataElementUidToIdentifierCache);
}
if (params.getCategoryOptionCombo() == null && !isSuper(user)) {
return events.stream().filter(ev -> ev.getAttributeCategoryOptions() != null && splitToArray(ev.getAttributeCategoryOptions(), TextUtils.SEMICOLON).size() == ev.getOptionSize()).collect(Collectors.toList());
}
return events;
}
use of org.apache.commons.lang3.ObjectUtils.firstNonNull in project dhis2-core by dhis2.
the class DefaultDataValueSetService method createDataValueSetImportContext.
private ImportContext createDataValueSetImportContext(ImportOptions options, DataValueSet data) {
options = ObjectUtils.firstNonNull(options, ImportOptions.getDefaultImportOptions());
final User currentUser = currentUserService.getCurrentUser();
boolean auditEnabled = config.isEnabled(CHANGELOG_AGGREGATE);
boolean hasSkipAuditAuth = currentUser != null && currentUser.isAuthorized(Authorities.F_SKIP_DATA_IMPORT_AUDIT);
boolean skipAudit = (options.isSkipAudit() && hasSkipAuditAuth) || !auditEnabled;
SystemSettingManager settings = systemSettingManager;
IdScheme dataElementIdScheme = createIdScheme(data.getDataElementIdSchemeProperty(), options, IdSchemes::getDataElementIdScheme);
IdScheme orgUnitIdScheme = createIdScheme(data.getOrgUnitIdSchemeProperty(), options, IdSchemes::getOrgUnitIdScheme);
IdScheme categoryOptComboIdScheme = createIdScheme(data.getCategoryOptionComboIdSchemeProperty(), options, IdSchemes::getCategoryOptionComboIdScheme);
IdScheme dataSetIdScheme = createIdScheme(data.getDataSetIdSchemeProperty(), options, IdSchemes::getDataSetIdScheme);
return ImportContext.builder().importOptions(options).summary(new ImportSummary().setImportOptions(options)).isIso8601(calendarService.getSystemCalendar().isIso8601()).skipLockExceptionCheck(!lockExceptionStore.anyExists()).i18n(i18nManager.getI18n()).currentUser(currentUser).currentOrgUnits(currentUserService.getCurrentUserOrganisationUnits()).hasSkipAuditAuth(hasSkipAuditAuth).skipAudit(skipAudit).idScheme(createIdScheme(data.getIdSchemeProperty(), options, IdSchemes::getIdScheme)).dataElementIdScheme(dataElementIdScheme).orgUnitIdScheme(orgUnitIdScheme).categoryOptComboIdScheme(categoryOptComboIdScheme).dataSetIdScheme(dataSetIdScheme).strategy(data.getStrategy() != null ? ImportStrategy.valueOf(data.getStrategy()) : options.getImportStrategy()).dryRun(data.getDryRun() != null ? data.getDryRun() : options.isDryRun()).skipExistingCheck(options.isSkipExistingCheck()).strictPeriods(options.isStrictPeriods() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_PERIODS)).strictDataElements(options.isStrictDataElements() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_DATA_ELEMENTS)).strictCategoryOptionCombos(options.isStrictCategoryOptionCombos() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS)).strictAttrOptionCombos(options.isStrictAttributeOptionCombos() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_ATTRIBUTE_OPTION_COMBOS)).strictOrgUnits(options.isStrictOrganisationUnits() || settings.getBoolSetting(SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS)).requireCategoryOptionCombo(options.isRequireCategoryOptionCombo() || settings.getBoolSetting(SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO)).requireAttrOptionCombo(options.isRequireAttributeOptionCombo() || settings.getBoolSetting(SettingKey.DATA_IMPORT_REQUIRE_ATTRIBUTE_OPTION_COMBO)).forceDataInput(inputUtils.canForceDataInput(currentUser, options.isForce())).dataElementCallable(new IdentifiableObjectCallable<>(identifiableObjectManager, DataElement.class, dataElementIdScheme, null)).orgUnitCallable(new IdentifiableObjectCallable<>(identifiableObjectManager, OrganisationUnit.class, orgUnitIdScheme, trimToNull(data.getOrgUnit()))).categoryOptionComboCallable(new CategoryOptionComboAclCallable(categoryService, categoryOptComboIdScheme, null)).attributeOptionComboCallable(new CategoryOptionComboAclCallable(categoryService, categoryOptComboIdScheme, null)).periodCallable(new PeriodCallable(periodService, null, trimToNull(data.getPeriod()))).dataValueBatchHandler(batchHandlerFactory.createBatchHandler(DataValueBatchHandler.class).init()).auditBatchHandler(skipAudit ? null : batchHandlerFactory.createBatchHandler(DataValueAuditBatchHandler.class).init()).singularNameForType(klass -> schemaService.getDynamicSchema(klass).getSingular()).build();
}
Aggregations