Skip to content

Commit

Permalink
[PAGOPA-2177] fix: changed URL handling, using URI class
Browse files Browse the repository at this point in the history
  • Loading branch information
andrea-deri committed Sep 24, 2024
1 parent 89fb3ce commit 63749e6
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,30 +43,29 @@ public class PaaInviaRTSenderService {
@Value("${wisp-converter.rt-send.avoid-scheduling-on-states}")
private Set<String> avoidSchedulingOnStates;

public void sendToCreditorInstitution(String url, InetSocketAddress proxyAddress, List<Pair<String, String>> headers, String payload) {
public void sendToCreditorInstitution(URI uri, InetSocketAddress proxyAddress, List<Pair<String, String>> headers, String payload) {

try {

// Generating the REST client, setting proxy specification if needed
RestClient client;
if (proxyAddress != null) {
client = RestClient.builder(ProxyUtility.getProxiedClient(proxyAddress))
.baseUrl(url)
.build();
} else {
client = restClientBuilder.build();
}

// Send the passed request payload to the passed URL
RestClient.RequestBodySpec bodySpec = client.post()
.uri(URI.create(url))
.uri(uri)
.body(payload);
for (Pair<String, String> header : headers) {
bodySpec.header(header.getFirst(), header.getSecond());
}

// Save an RE event in order to track the communication with creditor institution
generateREForRequestToCreditorInstitution(url, headers, payload);
generateREForRequestToCreditorInstitution(uri.toString(), headers, payload);

// Communicating with creditor institution sending the paaInviaRT request
ResponseEntity<String> response = bodySpec.retrieve().toEntity(String.class);
Expand All @@ -76,7 +75,7 @@ public void sendToCreditorInstitution(String url, InetSocketAddress proxyAddress
PaaInviaRTRisposta body = checkResponseValidity(response, bodyPayload);

// Save an RE event in order to track the response from creditor institution
generateREForResponseFromCreditorInstitution(url, response.getStatusCode().value(), response.getHeaders(), bodyPayload, OutcomeEnum.RECEIVED, null);
generateREForResponseFromCreditorInstitution(uri.toString(), response.getStatusCode().value(), response.getHeaders(), bodyPayload, OutcomeEnum.RECEIVED, null);

// check the response and if the outcome is KO, throw an exception
EsitoPaaInviaRT esitoPaaInviaRT = body.getPaaInviaRTRisposta();
Expand Down Expand Up @@ -111,7 +110,7 @@ public void sendToCreditorInstitution(String url, InetSocketAddress proxyAddress
int statusCode = error.getStatusCode().value();
String responseBody = error.getResponseBodyAsString();
String otherInfo = error.getStatusText();
generateREForResponseFromCreditorInstitution(url, statusCode, error.getResponseHeaders(), responseBody, OutcomeEnum.RECEIVED_FAILURE, otherInfo);
generateREForResponseFromCreditorInstitution(uri.toString(), statusCode, error.getResponseHeaders(), responseBody, OutcomeEnum.RECEIVED_FAILURE, otherInfo);
}

throw new AppException(AppErrorCodeMessageEnum.RECEIPT_GENERATION_GENERIC_ERROR, e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
Expand Down Expand Up @@ -352,16 +353,14 @@ From station identifier (the common one defined, not the payment reference), ret
from the cache and then generate the URL that will be used to send the paaInviaRT SOAP request.
*/
ConnectionDto stationConnection = station.getConnection();
String url = CommonUtility.constructUrl(
URI uri = CommonUtility.constructUrl(
stationConnection.getProtocol().getValue(),
stationConnection.getIp(),
stationConnection.getPort().intValue(),
station.getService() != null ? station.getService().getPath() : "",
null,
null
station.getService() != null ? station.getService().getPath() : ""
);
List<Pair<String, String>> headers = CommonUtility.constructHeadersForPaaInviaRT(url, station, stationInForwarderPartialPath, forwarderSubscriptionKey);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(url, station, apimPath);
List<Pair<String, String>> headers = CommonUtility.constructHeadersForPaaInviaRT(uri, station, stationInForwarderPartialPath, forwarderSubscriptionKey);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(uri, station, apimPath);

// idempotency key creation to check if the rt has already been sent
String idempotencyKey = sessionData.getCommonFields().getSessionId() + "_" + noticeNumber;
Expand All @@ -381,7 +380,7 @@ From station identifier (the common one defined, not the payment reference), ret
try {

// send the receipt to the creditor institution via the URL set in the station configuration
paaInviaRTSenderService.sendToCreditorInstitution(url, proxyAddress, headers, rawPayload);
paaInviaRTSenderService.sendToCreditorInstitution(uri, proxyAddress, headers, rawPayload);

// generate a new event in RE for store the successful sending of the receipt
generateREForSentRT(sessionData, iuv, noticeNumber);
Expand All @@ -400,7 +399,7 @@ From station identifier (the common one defined, not the payment reference), ret
generateREForNotSentRT(sessionData, iuv, noticeNumber, message);

// because of the not sent receipt, it is necessary to schedule a retry of the sending process for this receipt
scheduleRTSend(sessionData, url, proxyAddress, headers, rawPayload, station, iuv, noticeNumber, idempotencyKey, receiptType);
scheduleRTSend(sessionData, uri, proxyAddress, headers, rawPayload, station, iuv, noticeNumber, idempotencyKey, receiptType);
idempotencyStatus = IdempotencyStatusEnum.FAILED;
}

Expand Down Expand Up @@ -558,7 +557,7 @@ private String generatePayloadAsRawString(IntestazionePPT header, String signatu
}


public void scheduleRTSend(SessionDataDTO sessionData, String url, InetSocketAddress proxyAddress, List<Pair<String, String>> headers, String payload,
public void scheduleRTSend(SessionDataDTO sessionData, URI uri, InetSocketAddress proxyAddress, List<Pair<String, String>> headers, String payload,
StationDto station, String iuv, String noticeNumber, String idempotencyKey, ReceiptTypeEnum receiptType) {

try {
Expand All @@ -579,7 +578,7 @@ public void scheduleRTSend(SessionDataDTO sessionData, String url, InetSocketAdd
.primitive(PAA_INVIA_RT)
.partitionKey(LocalDate.ofInstant(Instant.now(), ZoneId.systemDefault()).toString())
.payload(AppBase64Util.base64Encode(ZipUtil.zip(payload)))
.url(url)
.url(uri.toString())
.proxyAddress(proxy)
.headers(formattedHeaders)
.retry(0)
Expand Down Expand Up @@ -745,21 +744,19 @@ public void sendRTKoFromSessionId(String sessionId, InternalStepStatus internalS
configurations);
StationDto station = stations.get(sessionDataDTO.getCommonFields().getStationId());
ConnectionDto stationConnection = station.getConnection();
String url = CommonUtility.constructUrl(
URI uri = CommonUtility.constructUrl(
stationConnection.getProtocol().getValue(),
stationConnection.getIp(),
stationConnection.getPort().intValue(),
station.getService() != null ? station.getService().getPath() : "",
null,
null
station.getService() != null ? station.getService().getPath() : ""
);
List<Pair<String, String>> headers = CommonUtility.constructHeadersForPaaInviaRT(url, station, stationInForwarderPartialPath, forwarderSubscriptionKey);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(url, station, apimPath);
List<Pair<String, String>> headers = CommonUtility.constructHeadersForPaaInviaRT(uri, station, stationInForwarderPartialPath, forwarderSubscriptionKey);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(uri, station, apimPath);
IdempotencyStatusEnum idempotencyStatus;
try {

// send the receipt to the creditor institution via the URL set in the station configuration
paaInviaRTSenderService.sendToCreditorInstitution(url, proxyAddress, headers, rtRawPayload);
paaInviaRTSenderService.sendToCreditorInstitution(uri, proxyAddress, headers, rtRawPayload);

// generate a new event in RE for store the successful sending of the receipt
generateREForSentRT(sessionDataDTO, rpt.getIuv(), null);
Expand All @@ -777,7 +774,7 @@ public void sendRTKoFromSessionId(String sessionId, InternalStepStatus internalS
generateREForNotSentRT(sessionDataDTO, rpt.getIuv(), null, messageException);

// because of the not sent receipt, it is necessary to schedule a retry of the sending process for this receipt
scheduleRTSend(sessionDataDTO, url, proxyAddress, headers, rtRawPayload, station, rpt.getIuv(), null, idempotencyKey, ReceiptTypeEnum.KO);
scheduleRTSend(sessionDataDTO, uri, proxyAddress, headers, rtRawPayload, station, rpt.getIuv(), null, idempotencyKey, ReceiptTypeEnum.KO);
idempotencyStatus = IdempotencyStatusEnum.FAILED;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.URI;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
Expand Down Expand Up @@ -224,15 +225,13 @@ public RecoveryProxyReceiptResponse recoverReceiptToBeSentByProxy(RecoveryProxyR
StationDto station = configCacheService.getStationByIdFromCache(stationId);

ConnectionDto stationConnection = station.getConnection();
String url = CommonUtility.constructUrl(
URI uri = CommonUtility.constructUrl(
stationConnection.getProtocol().getValue(),
stationConnection.getIp(),
stationConnection.getPort().intValue(),
station.getService() != null ? station.getService().getPath() : "",
null,
null
station.getService() != null ? station.getService().getPath() : ""
);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(url, station, apimPath);
InetSocketAddress proxyAddress = CommonUtility.constructProxyAddress(uri, station, apimPath);
if (proxyAddress != null) {
rtRequestEntity.setProxyAddress(String.format("%s:%s", proxyAddress.getHostString(), proxyAddress.getPort()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.LinkedList;
import java.util.List;
Expand Down Expand Up @@ -169,7 +170,7 @@ private boolean resendRTToCreditorInstitution(String receiptId, RTRequestEntity
}

String rawPayload = new String(unzippedPayload);
paaInviaRTSenderService.sendToCreditorInstitution(receipt.getUrl(), proxyAddress, extractHeaders(receipt.getHeaders()), rawPayload);
paaInviaRTSenderService.sendToCreditorInstitution(URI.create(receipt.getUrl()), proxyAddress, extractHeaders(receipt.getHeaders()), rawPayload);
rtRetryComosService.deleteRTRequestEntity(receipt);
log.debug("Sent receipt [{}]", receiptId);

Expand Down
18 changes: 12 additions & 6 deletions src/main/java/it/gov/pagopa/wispconverter/util/CommonUtility.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,16 @@ public static String getAppCode(AppErrorCodeMessageEnum error) {
return String.format("%s-%s", Constants.SERVICE_CODE_APP, error.getCode());
}

public static String constructUrl(String protocol, String hostname, int port, String path, String query, String fragment) {
public static URI constructUrl(String protocol, String hostname, int port, String path) {
try {
String query = null;
String pathMod = null;
if (null != path) {
if (path.contains("?")) {
String[] pathSplit = path.split("\\?", 1);
path = pathSplit[0];
query = pathSplit[1];
}
pathMod = path.startsWith("/") ? path : ("/" + path);
}

Expand All @@ -84,17 +90,17 @@ public static String constructUrl(String protocol, String hostname, int port, St
port,
pathMod,
query,
fragment).toString();
null);
} catch (Exception e) {
throw new AppException(AppErrorCodeMessageEnum.PARSING_GENERIC_ERROR);
}
}

public static List<Pair<String, String>> constructHeadersForPaaInviaRT(String startingUrl, StationDto station, String stationInForwarderPartialPath, String forwarderSubscriptionKey) {
public static List<Pair<String, String>> constructHeadersForPaaInviaRT(URI startingUri, StationDto station, String stationInForwarderPartialPath, String forwarderSubscriptionKey) {
List<Pair<String, String>> headers = new LinkedList<>();
headers.add(Pair.of("SOAPAction", "paaInviaRT"));
headers.add(Pair.of("Content-Type", "text/xml"));
if (startingUrl.contains(stationInForwarderPartialPath) && station.getService() != null) {
if (startingUri.getPath().contains(stationInForwarderPartialPath) && station.getService() != null) {
ServiceDto stationService = station.getService();
headers.add(Pair.of("X-Host-Url", stationService.getTargetHost() == null ? "ND" : stationService.getTargetHost()));
headers.add(Pair.of("X-Host-Port", stationService.getTargetPort() == null ? "ND" : String.valueOf(stationService.getTargetPort())));
Expand All @@ -104,10 +110,10 @@ public static List<Pair<String, String>> constructHeadersForPaaInviaRT(String st
return headers;
}

public static InetSocketAddress constructProxyAddress(String startingUrl, StationDto station, String apimPath) {
public static InetSocketAddress constructProxyAddress(URI startingUri, StationDto station, String apimPath) {
InetSocketAddress proxyAddress = null;

if (!startingUrl.contains(apimPath)) {
if (!startingUri.getPath().contains(apimPath)) {
ProxyDto proxyDto = station.getProxy();
if (proxyDto == null || proxyDto.getProxyHost() == null || proxyDto.getProxyPort() == null) {
throw new AppException(AppErrorCodeMessageEnum.CONFIGURATION_INVALID_STATION_PROXY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ void sendOkReceipt_notSent() throws Exception {

// mocking error response from creditor institution
doThrow(new AppException(AppErrorCodeMessageEnum.RECEIPT_GENERATION_ERROR_RESPONSE_FROM_CREDITOR_INSTITUTION, "PAA_ERRORE_RESPONSE", "PAA_ERRORE_RESPONSE", "Errore PA"))
.when(paaInviaRTSenderService).sendToCreditorInstitution(anyString(), any(), any(), anyString());
.when(paaInviaRTSenderService).sendToCreditorInstitution(any(), any(), any(), anyString());

mvc.perform(MockMvcRequestBuilders.post("/receipt/ok")
.accept(MediaType.APPLICATION_JSON)
Expand All @@ -231,7 +231,7 @@ void sendOkReceipt_notSent() throws Exception {
assertNotNull(result.getResponse());
});

verify(paaInviaRTSenderService, times(1)).sendToCreditorInstitution(anyString(), any(), any(), anyString());
verify(paaInviaRTSenderService, times(1)).sendToCreditorInstitution(any(), any(), any(), anyString());
}

@ParameterizedTest
Expand Down Expand Up @@ -427,7 +427,7 @@ void sendKoReceipt_notSent() throws Exception {
.paymentToken("token01")
.build();
doThrow(new AppException(AppErrorCodeMessageEnum.RECEIPT_GENERATION_ERROR_RESPONSE_FROM_CREDITOR_INSTITUTION, "PAA_ERRORE_RESPONSE", "PAA_ERRORE_RESPONSE", "Errore PA"))
.when(paaInviaRTSenderService).sendToCreditorInstitution(anyString(), any(), any(), anyString());
.when(paaInviaRTSenderService).sendToCreditorInstitution(any(), any(), any(), anyString());

mvc.perform(MockMvcRequestBuilders.post("/receipt/ko")
.accept(MediaType.APPLICATION_JSON)
Expand All @@ -440,6 +440,6 @@ void sendKoReceipt_notSent() throws Exception {
assertNotNull(result.getResponse());
});

verify(paaInviaRTSenderService, times(1)).sendToCreditorInstitution(anyString(), any(), any(), anyString());
verify(paaInviaRTSenderService, times(1)).sendToCreditorInstitution(any(), any(), any(), anyString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ void esitoOK() {

PaaInviaRTSenderService p = new PaaInviaRTSenderService(builder, reService, jaxbElementUtil);
org.springframework.test.util.ReflectionTestUtils.setField(p, "jaxbElementUtil", new JaxbElementUtil());
p.sendToCreditorInstitution("", null, List.of(Pair.of("soapaction", "paaInviaRT")), "");
p.sendToCreditorInstitution(URI.create("http://pagopa.mock.dev/"), null, List.of(Pair.of("soapaction", "paaInviaRT")), "");
assertTrue(true);
}

Expand Down Expand Up @@ -77,7 +77,7 @@ void esitoKO() {

PaaInviaRTSenderService p = new PaaInviaRTSenderService(builder, reService, jaxbElementUtil);
try {
p.sendToCreditorInstitution("", null, List.of(Pair.of("soapaction", "paaInviaRT")), "");
p.sendToCreditorInstitution(URI.create("http://pagopa.mock.dev/"), null, List.of(Pair.of("soapaction", "paaInviaRT")), "");
fail();
} catch (AppException e) {
assertTrue(true);
Expand Down

0 comments on commit 63749e6

Please sign in to comment.