Search in sources :

Example 1 with InvalidApiParameterException

use of org.ehrbase.api.exception.InvalidApiParameterException in project ehrbase by ehrbase.

the class TemplateServiceImp method findOperationalTemplate.

@Override
public String findOperationalTemplate(String templateId, OperationalTemplateFormat format) throws ObjectNotFoundException, InvalidApiParameterException, InternalServerException {
    Optional<OPERATIONALTEMPLATE> operationaltemplate;
    if (format.equals(OperationalTemplateFormat.XML)) {
        try {
            operationaltemplate = this.knowledgeCacheService.retrieveOperationalTemplate(templateId);
            if (!operationaltemplate.isPresent()) {
                throw new ObjectNotFoundException("template", "Template with the specified id does not exist");
            }
        } catch (NullPointerException e) {
            // TODO: is this NPE really thrown in case of not found template anymore?
            throw new ObjectNotFoundException("template", "Template with the specified id does not exist", e);
        }
    } else {
        // TODO only XML at the moment
        throw new InvalidApiParameterException("Requested operational template type not supported");
    }
    XmlOptions opts = new XmlOptions();
    opts.setSaveSyntheticDocumentElement(new QName("http://schemas.openehr.org/v1", "template"));
    return operationaltemplate.map(o -> o.xmlText(opts)).orElseThrow(() -> new InternalServerException("Failure while retrieving operational template"));
}
Also used : InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) TemplateService(org.ehrbase.api.service.TemplateService) TemplateMetaDataDto(org.ehrbase.response.ehrscape.TemplateMetaDataDto) OPERATIONALTEMPLATE(org.openehr.schemas.v1.OPERATIONALTEMPLATE) TemplateMetaData(org.ehrbase.ehr.knowledge.TemplateMetaData) ObjectNotFoundException(org.ehrbase.api.exception.ObjectNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) CARCHETYPEROOT(org.openehr.schemas.v1.CARCHETYPEROOT) Service(org.springframework.stereotype.Service) DSLContext(org.jooq.DSLContext) OperationalTemplateFormat(org.ehrbase.api.definitions.OperationalTemplateFormat) Logger(org.slf4j.Logger) StructuredStringFormat(org.ehrbase.response.ehrscape.StructuredStringFormat) Collectors(java.util.stream.Collectors) StructuredString(org.ehrbase.response.ehrscape.StructuredString) StandardCharsets(java.nio.charset.StandardCharsets) WebTemplate(org.ehrbase.webtemplate.model.WebTemplate) Objects(java.util.Objects) List(java.util.List) CompositionService(org.ehrbase.api.service.CompositionService) XmlOptions(org.apache.xmlbeans.XmlOptions) InternalServerException(org.ehrbase.api.exception.InternalServerException) InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) ServerConfig(org.ehrbase.api.definitions.ServerConfig) Optional(java.util.Optional) QName(javax.xml.namespace.QName) OBJECTID(org.openehr.schemas.v1.OBJECTID) CompositionFormat(org.ehrbase.response.ehrscape.CompositionFormat) Transactional(org.springframework.transaction.annotation.Transactional) OPERATIONALTEMPLATE(org.openehr.schemas.v1.OPERATIONALTEMPLATE) QName(javax.xml.namespace.QName) InternalServerException(org.ehrbase.api.exception.InternalServerException) ObjectNotFoundException(org.ehrbase.api.exception.ObjectNotFoundException) XmlOptions(org.apache.xmlbeans.XmlOptions)

Example 2 with InvalidApiParameterException

use of org.ehrbase.api.exception.InvalidApiParameterException in project ehrbase by ehrbase.

the class CompositionServiceImp method internalUpdate.

/**
 * Update of an existing composition. With optional custom contribution, or existing one will be
 * updated.
 *
 * @param compositionId  ID of existing composition
 * @param composition    RMObject instance of the given Composition which represents the new
 *                       version
 * @param systemId       Audit system; or NULL if contribution is given
 * @param committerId    Audit committer; or NULL if contribution is given
 * @param description    (Optional) Audit description; or NULL if contribution is given
 * @param contributionId NULL if new one should be created; or ID of given custom contribution
 * @return Version UID pointing to updated composition
 */
private ObjectVersionId internalUpdate(UUID compositionId, Composition composition, UUID systemId, UUID committerId, String description, UUID contributionId) {
    boolean result;
    try {
        var compositionAccess = I_CompositionAccess.retrieveInstance(getDataAccess(), compositionId);
        if (compositionAccess == null) {
            throw new ObjectNotFoundException(I_CompositionAccess.class.getName(), "Could not find composition: " + compositionId);
        }
        // validate RM composition
        validationService.check(composition);
        // Check if template ID is not the same in existing and given data -> error
        String existingTemplateId = compositionAccess.getContent().get(0).getTemplateId();
        String inputTemplateId = composition.getArchetypeDetails().getTemplateId().getValue();
        if (!existingTemplateId.equals(inputTemplateId)) {
            // check if base template ID doesn't match  (template ID schema: "$NAME.$LANG.v$VER")
            if (!existingTemplateId.split("\\.")[0].equals(inputTemplateId.split("\\.")[0])) {
                throw new InvalidApiParameterException("Can't update composition to have different template.");
            }
            // if base matches, check if given template ID is just a new version of the correct template
            int existingTemplateIdVersion = Integer.parseInt(existingTemplateId.split("\\.v")[1]);
            int inputTemplateIdVersion = Integer.parseInt(inputTemplateId.substring(inputTemplateId.lastIndexOf("\\.v") + 1));
            if (inputTemplateIdVersion < existingTemplateIdVersion) {
                throw new InvalidApiParameterException("Can't update composition with wrong template version bump.");
            }
        }
        // to keep reference to entry to update: pull entry out of composition access and replace
        // composition content with input, then write back to the original access
        List<I_EntryAccess> contentList = compositionAccess.getContent();
        contentList.get(0).setCompositionData(composition);
        compositionAccess.setContent(contentList);
        compositionAccess.setComposition(composition);
        if (contributionId != null) {
            // if custom contribution should be set
            compositionAccess.setContributionId(contributionId);
            result = compositionAccess.update(LocalDateTime.now(), contributionId);
        } else {
            // else existing one will be updated
            if (committerId == null || systemId == null) {
                throw new InternalServerException("Failed to update composition, missing mandatory audit meta data.");
            }
            result = compositionAccess.update(LocalDateTime.now(), committerId, systemId, description, ContributionChangeType.MODIFICATION);
        }
    } catch (ObjectNotFoundException | InvalidApiParameterException e) {
        // otherwise exceptions would always get sucked up by the catch below
        throw e;
    } catch (Exception e) {
        throw new InternalServerException(e);
    }
    if (!result) {
        throw new InternalServerException("Update failed on composition:" + compositionId);
    }
    return new ObjectVersionId(compositionId.toString(), this.getServerConfig().getNodename(), getLastVersionNumber(compositionId).toString());
}
Also used : InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) I_EntryAccess(org.ehrbase.dao.access.interfaces.I_EntryAccess) InternalServerException(org.ehrbase.api.exception.InternalServerException) StructuredString(org.ehrbase.response.ehrscape.StructuredString) ObjectVersionId(com.nedap.archie.rm.support.identification.ObjectVersionId) UnexpectedSwitchCaseException(org.ehrbase.api.exception.UnexpectedSwitchCaseException) ObjectNotFoundException(org.ehrbase.api.exception.ObjectNotFoundException) InternalServerException(org.ehrbase.api.exception.InternalServerException) ValidationException(org.ehrbase.api.exception.ValidationException) InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) UnprocessableEntityException(org.ehrbase.api.exception.UnprocessableEntityException) ObjectNotFoundException(org.ehrbase.api.exception.ObjectNotFoundException) I_CompositionAccess(org.ehrbase.dao.access.interfaces.I_CompositionAccess)

Example 3 with InvalidApiParameterException

use of org.ehrbase.api.exception.InvalidApiParameterException in project ehrbase by ehrbase.

the class KnowledgeCacheService method addOperationalTemplateIntern.

public String addOperationalTemplateIntern(byte[] content, boolean overwrite) {
    TemplateDocument document;
    try {
        document = TemplateDocument.Factory.parse(new ByteArrayInputStream(content));
    } catch (XmlException | IOException e) {
        throw new InvalidApiParameterException(e.getMessage());
    }
    OPERATIONALTEMPLATE template = document.getTemplate();
    if (template == null) {
        throw new InvalidApiParameterException("Could not parse input template");
    }
    if (template.getConcept() == null || template.getConcept().isEmpty()) {
        throw new IllegalArgumentException("Supplied template has nil or empty concept");
    }
    if (template.getDefinition() == null || template.getDefinition().isNil()) {
        throw new IllegalArgumentException("Supplied template has nil or empty definition");
    }
    if (template.getDescription() == null || !template.getDescription().validate()) {
        throw new IllegalArgumentException("Supplied template has nil or empty description");
    }
    if (!TemplateUtils.isSupported(template)) {
        throw new IllegalArgumentException(MessageFormat.format("The supplied template is not supported (unsupported types: {0})", String.join(",", TemplateUtils.UNSUPPORTED_RM_TYPES)));
    }
    String templateId;
    try {
        templateId = TemplateUtils.getTemplateId(template);
    } catch (IllegalArgumentException a) {
        throw new InvalidApiParameterException("Invalid template input content");
    }
    // pre-check: if already existing throw proper exception
    if (!allowTemplateOverwrite && !overwrite && retrieveOperationalTemplate(templateId).isPresent()) {
        throw new StateConflictException("Operational template with this template ID already exists: " + templateId);
    } else {
        invalidateCache(template);
    }
    templateStorage.storeTemplate(template);
    putIntoCache(template);
    if (cacheOptions.isPreBuildQueries()) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
        executor.submit(() -> {
            try {
                precalculateQueries(templateId);
            } catch (RuntimeException e) {
                log.error("An error occurred while processing template: {}", templateId);
            }
        });
    }
    // retrieve the template Id for this new entry
    return templateId;
}
Also used : InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) OPERATIONALTEMPLATE(org.openehr.schemas.v1.OPERATIONALTEMPLATE) TemplateDocument(org.openehr.schemas.v1.TemplateDocument) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlException(org.apache.xmlbeans.XmlException) IOException(java.io.IOException) StateConflictException(org.ehrbase.api.exception.StateConflictException) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 4 with InvalidApiParameterException

use of org.ehrbase.api.exception.InvalidApiParameterException in project ehrbase by ehrbase.

the class StatusAccess method internalUpdate.

private Boolean internalUpdate(LocalDateTime transactionTime) {
    auditDetailsAccess.commit();
    // new audit ID
    statusRecord.setHasAudit(auditDetailsAccess.getId());
    statusRecord.setSysTransaction(Timestamp.valueOf(transactionTime));
    try {
        return statusRecord.update() > 0;
    } catch (RuntimeException e) {
        throw new InvalidApiParameterException("Couldn't marshall given EHR_STATUS / OTHER_DETAILS, content probably breaks RM rules");
    }
}
Also used : InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException)

Example 5 with InvalidApiParameterException

use of org.ehrbase.api.exception.InvalidApiParameterException in project ehrbase by ehrbase.

the class StatusAccess method internalCommit.

private UUID internalCommit(LocalDateTime transactionTime) {
    auditDetailsAccess.setChangeType(I_ConceptAccess.fetchContributionChangeType(this, I_ConceptAccess.ContributionChangeType.CREATION));
    if (auditDetailsAccess.getChangeType() == null || auditDetailsAccess.getSystemId() == null || auditDetailsAccess.getCommitter() == null) {
        throw new InternalServerException("Illegal to commit AuditDetailsAccess without setting mandatory fields.");
    }
    UUID auditId = auditDetailsAccess.commit();
    statusRecord.setHasAudit(auditId);
    statusRecord.setSysTransaction(Timestamp.valueOf(transactionTime));
    statusRecord.setHasAudit(auditId);
    if (statusRecord.store() == 0) {
        throw new InvalidApiParameterException("Input EHR couldn't be stored; Storing EHR_STATUS failed");
    }
    return statusRecord.getId();
}
Also used : InvalidApiParameterException(org.ehrbase.api.exception.InvalidApiParameterException) InternalServerException(org.ehrbase.api.exception.InternalServerException) UUID(java.util.UUID)

Aggregations

InvalidApiParameterException (org.ehrbase.api.exception.InvalidApiParameterException)17 InternalServerException (org.ehrbase.api.exception.InternalServerException)11 UUID (java.util.UUID)9 ObjectNotFoundException (org.ehrbase.api.exception.ObjectNotFoundException)7 MediaType (org.springframework.http.MediaType)6 Optional (java.util.Optional)5 GetMapping (org.springframework.web.bind.annotation.GetMapping)5 OriginalVersion (com.nedap.archie.rm.changecontrol.OriginalVersion)4 EhrStatus (com.nedap.archie.rm.ehr.EhrStatus)4 ObjectVersionId (com.nedap.archie.rm.support.identification.ObjectVersionId)4 Objects (java.util.Objects)4 EhrService (org.ehrbase.api.service.EhrService)4 BaseController (org.ehrbase.rest.BaseController)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ResponseEntity (org.springframework.http.ResponseEntity)4 PathVariable (org.springframework.web.bind.annotation.PathVariable)4 RequestHeader (org.springframework.web.bind.annotation.RequestHeader)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 RequestParam (org.springframework.web.bind.annotation.RequestParam)4 RestController (org.springframework.web.bind.annotation.RestController)4