use of org.hisp.dhis.dxf2.events.trackedentity.Relationship in project dhis2-core by dhis2.
the class TrackedEntityInstanceAggregate method find.
/**
* Fetches a List of {@see TrackedEntityInstance} based on the list of
* primary keys and search parameters
*
* @param ids a List of {@see TrackedEntityInstance} Primary Keys
* @param params an instance of {@see TrackedEntityInstanceParams}
*
* @return a List of {@see TrackedEntityInstance} objects
*/
public List<TrackedEntityInstance> find(List<Long> ids, TrackedEntityInstanceParams params, TrackedEntityInstanceQueryParams queryParams) {
final User user = currentUserService.getCurrentUser();
if (!userGroupUIDCache.get(user.getUid()).isPresent() && !CollectionUtils.isEmpty(user.getGroups())) {
userGroupUIDCache.put(user.getUid(), user.getGroups().stream().map(group -> group.getUid()).collect(Collectors.toList()));
}
/*
* Create a context with information which will be used to fetch the
* entities
*/
AggregateContext ctx = securityCache.get(user.getUid(), userUID -> getSecurityContext(userUID, userGroupUIDCache.get(userUID).orElse(Lists.newArrayList()))).toBuilder().userId(user.getId()).superUser(user.isSuper()).params(params).queryParams(queryParams).build();
/*
* Async fetch Relationships for the given TrackedEntityInstance id
* (only if isIncludeRelationships = true)
*/
final CompletableFuture<Multimap<String, Relationship>> relationshipsAsync = conditionalAsyncFetch(ctx.getParams().isIncludeRelationships(), () -> trackedEntityInstanceStore.getRelationships(ids), getPool());
/*
* Async fetch Enrollments for the given TrackedEntityInstance id (only
* if isIncludeEnrollments = true)
*/
final CompletableFuture<Multimap<String, Enrollment>> enrollmentsAsync = conditionalAsyncFetch(ctx.getParams().isIncludeEnrollments(), () -> enrollmentAggregate.findByTrackedEntityInstanceIds(ids, ctx), getPool());
/*
* Async fetch all ProgramOwner for the given TrackedEntityInstance id
*/
final CompletableFuture<Multimap<String, ProgramOwner>> programOwnersAsync = conditionalAsyncFetch(ctx.getParams().isIncludeProgramOwners(), () -> trackedEntityInstanceStore.getProgramOwners(ids), getPool());
/*
* Async Fetch TrackedEntityInstances by id
*/
final CompletableFuture<Map<String, TrackedEntityInstance>> teisAsync = supplyAsync(() -> trackedEntityInstanceStore.getTrackedEntityInstances(ids, ctx), getPool());
/*
* Async fetch TrackedEntityInstance Attributes by TrackedEntityInstance
* id
*/
final CompletableFuture<Multimap<String, Attribute>> attributesAsync = supplyAsync(() -> trackedEntityInstanceStore.getAttributes(ids), getPool());
/*
* Async fetch Owned Tei mapped to the provided program attributes by
* TrackedEntityInstance id
*/
final CompletableFuture<Multimap<String, String>> ownedTeiAsync = supplyAsync(() -> trackedEntityInstanceStore.getOwnedTeis(ids, ctx), getPool());
/*
* Execute all queries and merge the results
*/
return allOf(teisAsync, attributesAsync, relationshipsAsync, enrollmentsAsync, ownedTeiAsync).thenApplyAsync(fn -> {
Map<String, TrackedEntityInstance> teis = teisAsync.join();
Multimap<String, Attribute> attributes = attributesAsync.join();
Multimap<String, Relationship> relationships = relationshipsAsync.join();
Multimap<String, Enrollment> enrollments = enrollmentsAsync.join();
Multimap<String, ProgramOwner> programOwners = programOwnersAsync.join();
Multimap<String, String> ownedTeis = ownedTeiAsync.join();
Stream<String> teiUidStream = teis.keySet().parallelStream();
if (queryParams.hasProgram()) {
teiUidStream = teiUidStream.filter(ownedTeis::containsKey);
}
return teiUidStream.map(uid -> {
TrackedEntityInstance tei = teis.get(uid);
tei.setAttributes(filterAttributes(attributes.get(uid), ownedTeis.get(uid), teiAttributesCache.get("ALL_ATTRIBUTES", s -> trackedEntityAttributeService.getTrackedEntityAttributesByTrackedEntityTypes()), programTeiAttributesCache.get("ATTRIBUTES_BY_PROGRAM", s -> trackedEntityAttributeService.getTrackedEntityAttributesByProgram()), ctx));
tei.setRelationships(new ArrayList<>(relationships.get(uid)));
tei.setEnrollments(filterEnrollments(enrollments.get(uid), ownedTeis.get(uid), ctx));
tei.setProgramOwners(new ArrayList<>(programOwners.get(uid)));
return tei;
}).collect(Collectors.toList());
}, getPool()).join();
}
use of org.hisp.dhis.dxf2.events.trackedentity.Relationship in project dhis2-core by dhis2.
the class JacksonRelationshipService method updateRelationshipJson.
@Override
public ImportSummary updateRelationshipJson(String id, InputStream inputStream, ImportOptions importOptions) throws IOException {
Relationship relationship = fromJson(inputStream, Relationship.class);
relationship.setRelationship(id);
return updateRelationship(relationship, updateImportOptions(importOptions));
}
use of org.hisp.dhis.dxf2.events.trackedentity.Relationship in project dhis2-core by dhis2.
the class AbstractTrackedEntityInstanceService method mergeOrDeleteTrackedEntityInstances.
// -------------------------------------------------------------------------
// CREATE, UPDATE or DELETE
// -------------------------------------------------------------------------
@Override
@Transactional
public ImportSummaries mergeOrDeleteTrackedEntityInstances(List<TrackedEntityInstance> trackedEntityInstances, ImportOptions importOptions, JobConfiguration jobId) {
notifier.clear(jobId).notify(jobId, "Importing tracked entities");
try {
ImportSummaries importSummaries = new ImportSummaries();
importOptions = updateImportOptions(importOptions);
List<TrackedEntityInstance> create = new ArrayList<>();
List<TrackedEntityInstance> update = new ArrayList<>();
List<TrackedEntityInstance> delete = new ArrayList<>();
// TODO: Check whether relationships are modified during
// create/update/delete TEI logic. Decide whether logic below can be
// removed
List<Relationship> relationships = getRelationships(trackedEntityInstances);
setTrackedEntityListByStrategy(trackedEntityInstances, importOptions, create, update, delete);
importSummaries.addImportSummaries(addTrackedEntityInstances(create, importOptions));
importSummaries.addImportSummaries(updateTrackedEntityInstances(update, importOptions));
importSummaries.addImportSummaries(deleteTrackedEntityInstances(delete, importOptions));
// TODO: Created importSummaries don't contain correct href (TEI
// endpoint instead of relationships is used)
importSummaries.addImportSummaries(relationshipService.processRelationshipList(relationships, importOptions));
if (ImportReportMode.ERRORS == importOptions.getReportMode()) {
importSummaries.getImportSummaries().removeIf(is -> !is.hasConflicts());
}
notifier.notify(jobId, NotificationLevel.INFO, "Import done", true).addJobSummary(jobId, importSummaries, ImportSummaries.class);
return importSummaries;
} catch (RuntimeException ex) {
log.error(DebugUtils.getStackTrace(ex));
notifier.notify(jobId, ERROR, "Process failed: " + ex.getMessage(), true);
return new ImportSummaries().addImportSummary(new ImportSummary(ImportStatus.ERROR, "The import process failed: " + ex.getMessage()));
}
}
use of org.hisp.dhis.dxf2.events.trackedentity.Relationship in project dhis2-core by dhis2.
the class AbstractTrackedEntityInstanceService method handleRelationships.
private ImportSummaries handleRelationships(TrackedEntityInstance dtoEntityInstance, org.hisp.dhis.trackedentity.TrackedEntityInstance daoEntityInstance, ImportOptions importOptions) {
ImportSummaries importSummaries = new ImportSummaries();
List<Relationship> create = new ArrayList<>();
List<Relationship> update = new ArrayList<>();
List<String> relationshipUids = dtoEntityInstance.getRelationships().stream().map(Relationship::getRelationship).collect(Collectors.toList());
List<Relationship> delete = daoEntityInstance.getRelationshipItems().stream().map(RelationshipItem::getRelationship).filter(relationship -> trackerAccessManager.canWrite(importOptions.getUser(), relationship).isEmpty()).filter(relationship -> isTeiPartOfRelationship(relationship, daoEntityInstance)).map(org.hisp.dhis.relationship.Relationship::getUid).filter((uid) -> !relationshipUids.contains(uid)).map(uid -> {
Relationship relationship = new Relationship();
relationship.setRelationship(uid);
return relationship;
}).collect(Collectors.toList());
for (Relationship relationship : dtoEntityInstance.getRelationships()) {
if (importOptions.getImportStrategy() == ImportStrategy.SYNC && dtoEntityInstance.isDeleted()) {
delete.add(relationship);
} else if (relationship.getRelationship() == null) {
org.hisp.dhis.dxf2.events.trackedentity.RelationshipItem relationshipItem = new org.hisp.dhis.dxf2.events.trackedentity.RelationshipItem();
if (!isTeiPartOfRelationship(relationship, daoEntityInstance)) {
relationshipItem.setTrackedEntityInstance(dtoEntityInstance);
relationship.setFrom(relationshipItem);
}
create.add(relationship);
} else {
if (isTeiPartOfRelationship(relationship, daoEntityInstance)) {
if (_relationshipService.relationshipExists(relationship.getRelationship())) {
update.add(relationship);
} else {
create.add(relationship);
}
} else {
String message = String.format("Can't update relationship '%s': TrackedEntityInstance '%s' is not the owner of the relationship", relationship.getRelationship(), daoEntityInstance.getUid());
importSummaries.addImportSummary(new ImportSummary(ImportStatus.ERROR, message).setReference(relationship.getRelationship()).incrementIgnored());
}
}
}
importSummaries.addImportSummaries(relationshipService.addRelationships(create, importOptions));
importSummaries.addImportSummaries(relationshipService.updateRelationships(update, importOptions));
importSummaries.addImportSummaries(relationshipService.deleteRelationships(delete, importOptions));
return importSummaries;
}
use of org.hisp.dhis.dxf2.events.trackedentity.Relationship in project dhis2-core by dhis2.
the class AbstractRelationshipService method updateRelationship.
@Override
@Transactional
public ImportSummary updateRelationship(Relationship relationship, ImportOptions importOptions) {
ImportSummary importSummary = new ImportSummary(relationship.getRelationship());
importOptions = updateImportOptions(importOptions);
// Set up cache if not set already
if (!cacheExists()) {
prepareCaches(Lists.newArrayList(relationship), importOptions.getUser());
}
org.hisp.dhis.relationship.Relationship daoRelationship = relationshipService.getRelationship(relationship.getRelationship());
checkRelationship(relationship, importSummary);
if (daoRelationship == null) {
String message = "Relationship '" + relationship.getRelationship() + "' does not exist";
importSummary.addConflict("Relationship", message);
importSummary.setStatus(ImportStatus.ERROR);
importSummary.getImportCount().incrementIgnored();
return importSummary;
}
List<String> errors = trackerAccessManager.canWrite(importOptions.getUser(), daoRelationship);
if (!errors.isEmpty() || importSummary.hasConflicts()) {
importSummary.setStatus(ImportStatus.ERROR);
importSummary.getImportCount().incrementIgnored();
if (!errors.isEmpty()) {
importSummary.setDescription(errors.toString());
}
return importSummary;
}
org.hisp.dhis.relationship.Relationship _relationship = createDAORelationship(relationship);
daoRelationship.setRelationshipType(_relationship.getRelationshipType());
daoRelationship.setTo(_relationship.getTo());
daoRelationship.setFrom(_relationship.getFrom());
relationshipService.updateRelationship(daoRelationship);
importSummary.setReference(daoRelationship.getUid());
importSummary.getImportCount().incrementUpdated();
return importSummary;
}
Aggregations