Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PRDP-61] chore: Refactor io client #71

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions src/main/java/it/gov/pagopa/receipt/pdf/notifier/ReceiptToIO.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
package it.gov.pagopa.receipt.pdf.notifier;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.OutputBinding;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.annotation.CosmosDBOutput;
import com.microsoft.azure.functions.annotation.CosmosDBTrigger;
import com.microsoft.azure.functions.annotation.FunctionName;
import it.gov.pagopa.receipt.pdf.notifier.entity.message.IOMessage;
import it.gov.pagopa.receipt.pdf.notifier.entity.receipt.ReasonError;
import it.gov.pagopa.receipt.pdf.notifier.entity.receipt.Receipt;
import it.gov.pagopa.receipt.pdf.notifier.entity.receipt.enumeration.ReceiptStatusType;
import it.gov.pagopa.receipt.pdf.notifier.model.enumeration.UserNotifyStatus;
import it.gov.pagopa.receipt.pdf.notifier.model.enumeration.UserType;
import it.gov.pagopa.receipt.pdf.notifier.service.ReceiptToIOService;
import it.gov.pagopa.receipt.pdf.notifier.service.impl.ReceiptToIOServiceImpl;
import it.gov.pagopa.receipt.pdf.notifier.utils.ReceiptToIOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
Expand Down Expand Up @@ -86,7 +87,7 @@ public void processReceiptToIO(
connectionStringSetting = "COSMOS_RECEIPTS_CONN_STRING")
OutputBinding<List<IOMessage>> documentMessages,
final ExecutionContext context
) throws JsonProcessingException {
) {

logger.info("[{}] function called at {}", context.getFunctionName(), LocalDateTime.now());
AtomicInteger discarder = new AtomicInteger();
Expand Down Expand Up @@ -120,14 +121,7 @@ public void processReceiptToIO(
usersToBeVerified.put(UserType.PAYER, payerNotifyStatus);
}

boolean boolQueueSent = false;
try {
boolQueueSent = this.receiptToIOService.verifyMessagesNotification(usersToBeVerified, messagesNotified, receipt);
} catch (JsonProcessingException e) {
receipt.setStatus(ReceiptStatusType.IO_ERROR_TO_NOTIFY);
int code = ReceiptToIOUtils.getCodeOrDefault(e);
ReceiptToIOUtils.buildReasonError(e.getMessage(), code);
}
boolean boolQueueSent = this.receiptToIOService.verifyMessagesNotification(usersToBeVerified, messagesNotified, receipt);

if(boolQueueSent){
queueSent.getAndIncrement();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package it.gov.pagopa.receipt.pdf.notifier.client;

import it.gov.pagopa.receipt.pdf.notifier.exception.IOAPIException;
import it.gov.pagopa.receipt.pdf.notifier.model.io.IOProfilePayload;
import it.gov.pagopa.receipt.pdf.notifier.model.io.message.MessagePayload;

import java.net.http.HttpResponse;

/**
* Client for invoking IO APIs
*/
public interface IOClient {

/**
* Get a User Profile.
* <p>
* Returns the preferences for the user identified by the fiscal code provided in the request body.
* The field &#x60;sender_allowed&#x60; is set fo &#x60;false&#x60; in case the service which is calling the API has been disabled by the user.
*
* @param fiscalCodePayload the {@link IOProfilePayload} serialized as String
* @return the {@link HttpResponse} of the IO API
* @throws IOAPIException If fail to call the API
*/
HttpResponse<String> getProfile(String fiscalCodePayload) throws IOAPIException;

/**
* Submit a Message passing the user fiscal_code in the request body
* <p>
* Submits a message to a user with STANDARD or ADVANCED features based on &#x60;feature_level_type&#x60; value.
* On error, the reason is returned in the response payload. In order to call &#x60;submitMessageforUser&#x60;,
* before sending any message, the sender MUST call &#x60;getProfile&#x60; and check that the profile exists
* (for the specified fiscal code) and that the &#x60;sender_allowed&#x60; field of the user&#39;s profile it set to &#x60;true&#x60;.
*
* @param messagePayload the {@link MessagePayload} serialized as String
* @return the {@link HttpResponse} of the IO API
* @throws IOAPIException If fail to call the API
*/
HttpResponse<String> submitMessage(String messagePayload) throws IOAPIException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package it.gov.pagopa.receipt.pdf.notifier.client.impl;

import it.gov.pagopa.receipt.pdf.notifier.client.IOClient;
import it.gov.pagopa.receipt.pdf.notifier.exception.IOAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
* {@inheritDoc}
*/
public class IOClientImpl implements IOClient {

private final Logger logger = LoggerFactory.getLogger(IOClientImpl.class);

private static final String IO_API_BASE_PATH = System.getenv().getOrDefault("IO_API_BASE_PATH", "https://api.uat.platform.pagopa.it/mock-io/api/v1");
private static final String IO_API_PROFILES_PATH = System.getenv().getOrDefault("IO_API_PROFILES_PATH", "/profiles");
private static final String IO_API_MESSAGES_PATH = System.getenv().getOrDefault("IO_API_MESSAGES_PATH", "/messages");
private static final String OCP_APIM_SUBSCRIPTION_KEY = System.getenv().getOrDefault("OCP_APIM_SUBSCRIPTION_KEY", "");
private static final String OCP_APIM_HEADER_KEY = System.getenv().getOrDefault("OCP_APIM_HEADER_KEY", "Ocp-Apim-Subscription-Key");

private static final String CONTENT_TYPE_JSON = "application/json";
private static final int IO_API_IO_ERROR = 800;
private static final int IO_API_UNEXPECTED_ERROR = 801;

private final HttpClient client;

private static IOClient instance = null;

public static IOClient getInstance() {
if (instance == null) {
instance = new IOClientImpl();
}
return instance;
}

private IOClientImpl() {
this.client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
}

IOClientImpl(HttpClient client) {
this.client = client;
}

/**
* {@inheritDoc}
*/
@Override
public HttpResponse<String> getProfile(String fiscalCodePayload) throws IOAPIException {
String uri = String.format("%s%s", IO_API_BASE_PATH, IO_API_PROFILES_PATH);

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.version(HttpClient.Version.HTTP_2)
.header("Content-Type", CONTENT_TYPE_JSON)
.header(OCP_APIM_HEADER_KEY, OCP_APIM_SUBSCRIPTION_KEY)
.POST(HttpRequest.BodyPublishers.ofString(fiscalCodePayload))
.build();

return makeCall(request);
}

/**
* {@inheritDoc}
*/
@Override
public HttpResponse<String> submitMessage(String messagePayload) throws IOAPIException {
String uri = String.format("%s%s", IO_API_BASE_PATH, IO_API_MESSAGES_PATH);

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(uri))
.version(HttpClient.Version.HTTP_2)
.header("Content-Type", CONTENT_TYPE_JSON)
.header(OCP_APIM_HEADER_KEY, OCP_APIM_SUBSCRIPTION_KEY)
.POST(HttpRequest.BodyPublishers.ofString(messagePayload))
.build();

return makeCall(request);
}

private HttpResponse<String> makeCall(HttpRequest request) throws IOAPIException {
try {
return client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
throw new IOAPIException("I/O error when invoking IO API", IO_API_IO_ERROR, e);
} catch (InterruptedException e) {
logger.warn("This thread was interrupted, restoring the state");
Thread.currentThread().interrupt();
throw new IOAPIException("Unexpected error when invoking IO API, the thread was interrupted", IO_API_UNEXPECTED_ERROR, e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package it.gov.pagopa.receipt.pdf.notifier.exception;

import lombok.Getter;

/**
* Thrown in case an error occur when invoking IO APIs
*/
@Getter
public class IOAPIException extends Exception {

private final int statusCode;

/**
* Constructs new exception with provided message
*
* @param message Detail message
* @param statusCode status code
*/
public IOAPIException(String message, int statusCode) {
super(message);
this.statusCode = statusCode;
}

/**
* Constructs new exception with provided message
*
* @param message Detail message
* @param statusCode status code
* @param cause Exception causing the constructed one
*/
public IOAPIException(String message, int statusCode, Throwable cause) {
super(message, cause);
this.statusCode = statusCode;
}
}

This file was deleted.

Loading
Loading