Skip to content

Commit

Permalink
Merge branch 'develop' into feature/otel-config
Browse files Browse the repository at this point in the history
  • Loading branch information
vincenzo-ingenito committed Apr 11, 2024
2 parents b459b54 + 7d22507 commit 0bef454
Show file tree
Hide file tree
Showing 13 changed files with 131 additions and 56 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;

import it.finanze.sanita.fse2.ms.gtw.dispatcher.client.RestTemplateResponseErrorHandler;

@SpringBootApplication
public class DispatcherApplication {

Expand All @@ -31,7 +34,21 @@ public static void main(String[] args) {
*/
@Bean
@Qualifier("restTemplate")
@Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}

/**
* Definizione rest template.
*
* @return rest template
*/
@Bean
@Qualifier("restTemplateIni")
public RestTemplate restTemplateIni() {
RestTemplate rt = new RestTemplate();
rt.setErrorHandler(new RestTemplateResponseErrorHandler());
return rt;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package it.finanze.sanita.fse2.ms.gtw.dispatcher.client;


import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;

import com.google.gson.Gson;

import it.finanze.sanita.fse2.ms.gtw.dispatcher.dto.response.ErrorResponseDTO;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.exceptions.BusinessException;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.exceptions.NoRecordFoundException;


@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {

@Override
public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
return (httpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR ||
httpResponse.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR);
}

@Override
public void handleError(ClientHttpResponse httpResponse) throws IOException {
String result = IOUtils.toString(httpResponse.getBody(), StandardCharsets.UTF_8);
ErrorResponseDTO error = new Gson().fromJson(result, ErrorResponseDTO.class);
if (httpResponse.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
throw new BusinessException(error);
} else if(httpResponse.getStatusCode() == HttpStatus.NOT_FOUND){
throw new NoRecordFoundException(error);
} else {
throw new BusinessException("Generic error");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@
*/
package it.finanze.sanita.fse2.ms.gtw.dispatcher.client.impl;

import static it.finanze.sanita.fse2.ms.gtw.dispatcher.client.routes.base.ClientRoutes.Ini.DELETE_PATH;
import static it.finanze.sanita.fse2.ms.gtw.dispatcher.client.routes.base.ClientRoutes.Ini.REFERENCE_PATH;
import static it.finanze.sanita.fse2.ms.gtw.dispatcher.client.routes.base.ClientRoutes.Ini.UPDATE_PATH;
import static org.springframework.http.HttpMethod.DELETE;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.HttpMethod.PUT;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;

import it.finanze.sanita.fse2.ms.gtw.dispatcher.client.IIniClient;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.client.impl.base.AbstractClient;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.client.routes.IniClientRoutes;
Expand All @@ -21,16 +37,8 @@
import it.finanze.sanita.fse2.ms.gtw.dispatcher.dto.response.GetMergedMetadatiDTO;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.dto.response.IniReferenceResponseDTO;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.dto.response.IniTraceResponseDTO;
import it.finanze.sanita.fse2.ms.gtw.dispatcher.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;

import static it.finanze.sanita.fse2.ms.gtw.dispatcher.client.routes.base.ClientRoutes.Ini.*;
import static org.springframework.http.HttpMethod.*;

@Slf4j
@Component
Expand All @@ -41,6 +49,10 @@ public class IniClient extends AbstractClient implements IIniClient {

@Autowired
private IniClientRoutes routes;

@Autowired
@Qualifier("restTemplateIni")
private RestTemplate restTemplateIni;

@Override
public IniTraceResponseDTO delete(final DeleteRequestDTO request) {
Expand Down Expand Up @@ -102,6 +114,7 @@ public IniTraceResponseDTO update(IniMetadataUpdateReqDTO request) {
return output;
}


@Override
public GetMergedMetadatiDTO metadata(final MergedMetadatiRequestDTO request) {

Expand All @@ -111,14 +124,14 @@ public GetMergedMetadatiDTO metadata(final MergedMetadatiRequestDTO request) {
log.debug("{} - Executing request: {}", routes.identifier(), endpoint);

try {
// Execute request
ResponseEntity<GetMergedMetadatiDTO> response = client.exchange(endpoint,PUT,new HttpEntity<>(request),GetMergedMetadatiDTO.class);
// Retrieve body
ResponseEntity<GetMergedMetadatiDTO> response = restTemplateIni.exchange(endpoint,PUT,new HttpEntity<>(request),GetMergedMetadatiDTO.class);
output = response.getBody();
} catch (RestClientResponseException ex) {
toServerResponseEx(routes.identifier(), routes.microservice(), ex, METADATA_PATH);
} catch (ResourceAccessException ex) {
throw new BusinessException("Timeout error while call merge metadati");
}

return output;
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private void errorHandler(final HttpStatusCodeException e1) {
// 404 Not found.
if (HttpStatus.NOT_FOUND.equals(e1.getStatusCode())) {
ErrorResponseDTO error = ErrorResponseDTO.builder().detail("No Record Found").build();
throw new NoRecordFoundException(error,e1.getStatusCode().value());
throw new NoRecordFoundException(error);
}

// 500 Internal Server Error.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ protected ResponseEntity<ErrorResponseDTO> handleRecordNotFoundException(NoRecor
detail = ex.getError().getDetail();
}
ErrorResponseDTO out = new ErrorResponseDTO(getLogTraceInfo(), RestExecutionResultEnum.RECORD_NOT_FOUND.getType(), RestExecutionResultEnum.RECORD_NOT_FOUND.getTitle(), detail , status, ErrorInstanceEnum.RECORD_NOT_FOUND.getInstance());
if(ex.getError()!=null) {
out = ex.getError();
}

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON);
Expand Down Expand Up @@ -238,8 +241,12 @@ protected ResponseEntity<ErrorResponseDTO> handleGenericException(final Exceptio
protected ResponseEntity<ErrorResponseDTO> handleBusinessException(final BusinessException ex, final WebRequest request) {
int status = 500;

ErrorResponseDTO out = new ErrorResponseDTO(getLogTraceInfo(), RestExecutionResultEnum.GENERIC_ERROR.getType(), RestExecutionResultEnum.GENERIC_ERROR.getTitle(), ex.getMessage(), status, ErrorInstanceEnum.NO_INFO.getInstance());

LogTraceInfoDTO traceInfo = getLogTraceInfo();
ErrorResponseDTO out = new ErrorResponseDTO(traceInfo, RestExecutionResultEnum.GENERIC_ERROR.getType(), RestExecutionResultEnum.GENERIC_ERROR.getTitle(),
ex.getMessage(), status, ErrorInstanceEnum.NO_INFO.getInstance());
if(ex.getError()!=null) {
out = ex.getError();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ public ResponseWifDTO updateMetadata(final String idDoc, final PublicationMetada
IniTraceResponseDTO res = iniClient.update(new IniMetadataUpdateReqDTO(metadatiToUpdate.getMarshallResponse(), jwtPayloadToken,metadatiToUpdate.getDocumentType(),wif,
metadatiToUpdate.getAdministrativeRequest(), metadatiToUpdate.getAuthorInstitution()));
// Check response errors
if(!StringUtility.isNullOrEmpty(res.getErrorMessage())) {
if(Boolean.FALSE.equals(res.getEsito())) {
// Send to indexer
kafkaSRV.sendUpdateRequest(wif, new IniMetadataUpdateReqDTO(metadatiToUpdate.getMarshallResponse(), jwtPayloadToken, metadatiToUpdate.getDocumentType(), wif,
metadatiToUpdate.getAdministrativeRequest(), metadatiToUpdate.getAuthorInstitution()));
Expand Down Expand Up @@ -455,7 +455,8 @@ private ValidationDataDTO executePublicationReplace(final ValidationCreationInpu
private ResourceDTO callFhirMappingEngine(String transformId, String engineId,
final JWTPayloadDTO jwtPayloadToken, PublicationCreateReplaceMetadataDTO jsonObj, final byte[] bytePDF,
final String cda, final String documentSha256) {
final ResourceDTO fhirResourcesDTO = documentReferenceSRV.createFhirResources(cda,jwtPayloadToken.getSubject_role(), jsonObj, bytePDF.length, documentSha256,transformId, engineId);
final ResourceDTO fhirResourcesDTO = documentReferenceSRV.createFhirResources(cda,jwtPayloadToken.getSubject_role(), jsonObj, bytePDF.length, documentSha256,transformId, engineId,
jwtPayloadToken.getSubject_organization_id());

if(!isNullOrEmpty(fhirResourcesDTO.getErrorMessage())) {
final ErrorResponseDTO error = ErrorResponseDTO.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
*/
package it.finanze.sanita.fse2.ms.gtw.dispatcher.exceptions;

import it.finanze.sanita.fse2.ms.gtw.dispatcher.dto.response.ErrorResponseDTO;
import lombok.Getter;

/**
* Generic business exception.
*/
Expand All @@ -20,7 +23,11 @@ public class BusinessException extends RuntimeException {
*
*/
private static final long serialVersionUID = 4420700371354323215L;


@Getter
private ErrorResponseDTO error;


/**
* Message constructor.
*
Expand Down Expand Up @@ -49,4 +56,8 @@ public BusinessException(final Exception e) {
super(e);
}

public BusinessException(ErrorResponseDTO inError) {
error = inError;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,9 @@ public class NoRecordFoundException extends RuntimeException {
@Getter
private ErrorResponseDTO error;

@Getter
private Integer status;

public NoRecordFoundException(ErrorResponseDTO inError, Integer inStatus) {
public NoRecordFoundException(ErrorResponseDTO inError) {
error = inError;
status = inStatus;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@

public interface IFhirSRV {

ResourceDTO createFhirResources(final String cda,
String authorRole, PublicationCreateReplaceMetadataDTO requestBody,
Integer size, String hash, String transformId, String engineId);
ResourceDTO createFhirResources(String cda, String authorRole, PublicationCreateReplaceMetadataDTO requestBody,
Integer size, String hash, String transformId, String engineId, String organizationId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
@Slf4j
public class FhirSRV implements IFhirSRV {

private static final String PATH_ID = "ClinicalDocument > id";
private static final String SOURCE_ID_PREFIX = "2.16.840.1.113883.2.9.2.";
private static final String PATH_PATIENT_ID = "ClinicalDocument > recordTarget > patientRole> id";
private static final String EXTENSION_ATTRIBUTE = "extension";

Expand All @@ -58,7 +58,7 @@ public class FhirSRV implements IFhirSRV {

@Override
public ResourceDTO createFhirResources(final String cda, String authorRole,final PublicationCreateReplaceMetadataDTO requestBody,
final Integer size, final String hash, String transformId, String engineId) {
final Integer size, final String hash, String transformId, String engineId, String organizationId) {

final ResourceDTO output = new ResourceDTO();
final org.jsoup.nodes.Document docCDA = Jsoup.parse(cda);
Expand All @@ -77,7 +77,7 @@ public ResourceDTO createFhirResources(final String cda, String authorRole,final

try {
final SubmissionSetEntryDTO submissionSetEntryDTO = createSubmissionSetEntry(docCDA, requestBody.getTipoAttivitaClinica().getCode(),
requestBody.getIdentificativoSottomissione(),authorSlot);
requestBody.getIdentificativoSottomissione(),authorSlot,organizationId);
output.setSubmissionSetEntryJson(StringUtility.toJSON(submissionSetEntryDTO));
} catch(final Exception ex) {
output.setErrorMessage(ex.getCause().getCause().getMessage());
Expand Down Expand Up @@ -130,22 +130,16 @@ private FhirResourceDTO buildFhirResourceDTO(final DocumentReferenceDTO document
}


private SubmissionSetEntryDTO createSubmissionSetEntry(final org.jsoup.nodes.Document docCDA,
final String contentTypeCode, final String identificativoSottomissione,
AuthorSlotDTO authorSlotDTO) {
private SubmissionSetEntryDTO createSubmissionSetEntry(final org.jsoup.nodes.Document docCDA, final String contentTypeCode, final String identificativoSottomissione,
AuthorSlotDTO authorSlotDTO, String organizationId) {

SubmissionSetEntryDTO sse = new SubmissionSetEntryDTO();

sse.setAuthor(authorSlotDTO.getAuthor());
sse.setAuthorInstitution(authorSlotDTO.getAuthorInstitution());
sse.setAuthorRole(authorSlotDTO.getAuthorRole());
sse.setPatientId(buildPatient(docCDA));
String sourceIdRoot = "";
final Element idPath = docCDA.select(PATH_ID).first();
if (idPath != null) {
sourceIdRoot = idPath.attr("root");
sse.setSourceId(sourceIdRoot.substring(0, sourceIdRoot.length()-4));
}
sse.setSourceId(SOURCE_ID_PREFIX+organizationId);
sse.setUniqueID(identificativoSottomissione);

sse.setSubmissionTime(new SimpleDateFormat(Constants.Misc.INI_DATE_PATTERN).format(new Date()));
Expand Down Expand Up @@ -195,7 +189,6 @@ private DocumentEntryDTO createDocumentEntry(final org.jsoup.nodes.Document docC
}

de.setUniqueId(requestBody.getIdentificativoDoc());

de.setMimeType("application/pdf+text/x-cda-r2+xml");
de.setCreationTime(new SimpleDateFormat(Constants.Misc.INI_DATE_PATTERN).format(new Date()));
de.setHash(hash);
Expand All @@ -206,14 +199,12 @@ private DocumentEntryDTO createDocumentEntry(final org.jsoup.nodes.Document docC
administrativeRequestList.add(en.getCode() + "^" + en.getDescription());
}
de.setAdministrativeRequest(administrativeRequestList);

}

de.setAuthorRole(authorSlotDTO.getAuthorRole());
de.setAuthorInstitution(authorSlotDTO.getAuthorInstitution());
de.setAuthor(authorSlotDTO.getAuthor());


ValidationUtility.repositoryUniqueIdValidation(requestBody.getIdentificativoRep());
de.setRepositoryUniqueId(requestBody.getIdentificativoRep());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ void createDocumentReferenceOkTest() {
String cda = new String(cdaFile);
PublicationCreationReqDTO reqDTO = buildPublicationReqDTO(workflowInstanceId);
String documentSha = StringUtility.encodeSHA256(cdaFile);
ResourceDTO resourceDTO = documentReferenceSRV.createFhirResources(cda,"",reqDTO, documentSha.length(), documentSha, "", "");
ResourceDTO resourceDTO = documentReferenceSRV.createFhirResources(cda,"",reqDTO, documentSha.length(), documentSha, "", "","");
assertNotNull(resourceDTO.getDocumentEntryJson());
assertNotNull(resourceDTO.getSubmissionSetEntryJson());
assertNull(resourceDTO.getErrorMessage());
Expand Down Expand Up @@ -124,7 +124,7 @@ void createDocumentReferenceErrorTest() {
PublicationCreationReqDTO reqDTO = buildPublicationReqDTO(workflowInstanceId);
String documentSha = StringUtility.encodeSHA256(cdaFile);
ResourceDTO resourceDTO = documentReferenceSRV.createFhirResources(cda, "",reqDTO, documentSha.length(), documentSha,
"PersonId", "");
"PersonId", "", "");
ResourceDTO expectedOutputDTO = new ResourceDTO();
expectedOutputDTO.setErrorMessage("errorMessage");
assertEquals(expectedOutputDTO, resourceDTO);
Expand All @@ -143,7 +143,7 @@ void createDocumentReferenceConnectionRefusedTest() {
PublicationCreationReqDTO reqDTO = buildPublicationReqDTO(workflowInstanceId);
String documentSha = StringUtility.encodeSHA256(cdaFile);
assertThrows(ConnectionRefusedException.class, () -> documentReferenceSRV.createFhirResources(cda,"", reqDTO, documentSha.length(), documentSha,
"PersonId", ""));
"PersonId", "",""));
}

@Test
Expand All @@ -159,6 +159,6 @@ void createDocumentReferenceErrorBusinessException() {
PublicationCreationReqDTO reqDTO = buildPublicationReqDTO(workflowInstanceId);
String documentSha = StringUtility.encodeSHA256(cdaFile);
assertThrows(BusinessException.class, () -> documentReferenceSRV.createFhirResources(cda,"", reqDTO, documentSha.length(), documentSha,
"PersonId", ""));
"PersonId", "", ""));
}
}
Loading

0 comments on commit 0bef454

Please sign in to comment.