// Esempio di integrazione con le API di Hub Multicanale (Java 11 o successivo, nessuna libreria esterna). // Esecuzione diretta: java Esempio.java // Flusso: lasciapassare -> enti -> crea lotto -> aggiungi posizione -> carica PDF -> conferma -> stato -> cambiamenti. // Per brevità il JSON è scritto a mano e letto con espressioni regolari: nel gestionale usa la tua libreria JSON. import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Signature; import java.security.interfaces.ECPrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Esempio { // ===== Impostazioni: per la produzione cambiano solo BASE, CLIENTE, KID e il file della chiave ===== static final String BASE = env("HUB_BASE", "https://supabase-test.infotecservizi.it/functions/v1"); static final String CLIENTE = env("HUB_CLIENTE", "IL-TUO-IDENTIFICATIVO-CLIENTE"); static final String KID = env("HUB_KID", "il-tuo-kid"); static final String CHIAVE = env("HUB_CHIAVE", "./privata-pkcs8.pem"); // PEM «BEGIN PRIVATE KEY», EC P-256 o RSA static final String CF_ENTE = env("HUB_CF_ENTE", "CODICE-FISCALE-ENTE"); static final String PDF = env("HUB_PDF", "./atto.pdf"); // ==================================================================================================== static final HttpClient HTTP = HttpClient.newHttpClient(); static String env(String nome, String predefinito) { String v = System.getenv(nome); return v == null ? predefinito : v; } static String b64u(byte[] b) { return Base64.getUrlEncoder().withoutPadding().encodeToString(b); } static String enc(String s) { return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20"); } public static void main(String[] args) throws Exception { String token = lasciapassare(); String auth = "Bearer " + token; String L = BASE + "/api-sh/enti/" + enc(CF_ENTE) + "/lotti"; String idLotto = "ESEMPIO-" + System.currentTimeMillis(); chiama(HttpRequest.newBuilder(URI.create(BASE + "/api-sh/enti")).header("Authorization", auth).GET()); String lotto = chiama(HttpRequest.newBuilder(URI.create(L)).header("Authorization", auth) .header("Content-Type", "application/json").header("Idempotency-Key", idLotto) .POST(HttpRequest.BodyPublishers.ofString("{\"scenario\":\"posta\",\"id_lotto_esterno\":\"" + idLotto + "\",\"titolo\":\"Lotto d'esempio\",\"opzioni\":{\"prodotto\":\"ordinaria\",\"stampa\":{\"colore\":false,\"fronte_retro\":true}}}"))); String codice = campo(lotto, "codice_lotto"); String protocollo = idLotto + "-1"; chiama(HttpRequest.newBuilder(URI.create(L + "/" + codice + "/posizioni")).header("Authorization", auth) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"posizioni\":[{\"protocollo_pa\":\"" + protocollo + "\",\"causale\":\"Comunicazione d'esempio\"," + "\"destinatario\":{\"cf_piva\":\"RSSMRA85T10A562S\",\"tipo_persona\":\"fisica\",\"denominazione\":\"Mario Rossi (prova)\"}," + "\"indirizzo\":{\"indirizzo\":\"Via Roma 1\",\"cap\":\"00187\",\"comune\":\"Roma\",\"provincia\":\"RM\",\"stato\":\"IT\"}," + "\"documenti\":[{\"tipo\":\"atto\",\"nome\":\"atto.pdf\"}]}]}"))); byte[] pdf = Files.readAllBytes(Path.of(PDF)); StringBuilder sha = new StringBuilder(); for (byte b : MessageDigest.getInstance("SHA-256").digest(pdf)) sha.append(String.format("%02x", b)); chiama(HttpRequest.newBuilder(URI.create(L + "/" + codice + "/posizioni/" + enc(protocollo) + "/documenti/atto.pdf")) .header("Authorization", auth).header("Content-Type", "application/pdf").header("X-Content-SHA256", sha.toString()) .PUT(HttpRequest.BodyPublishers.ofByteArray(pdf))); chiama(HttpRequest.newBuilder(URI.create(L + "/" + codice + "/conferma")).header("Authorization", auth).POST(HttpRequest.BodyPublishers.noBody())); chiama(HttpRequest.newBuilder(URI.create(L + "/" + codice)).header("Authorization", auth).GET()); String cambi = chiama(HttpRequest.newBuilder(URI.create(BASE + "/api-sh/enti/" + enc(CF_ENTE) + "/cambiamenti")).header("Authorization", auth).GET()); System.out.println("Segnalibro da conservare: " + (campo(cambi, "segnalibro") != null ? "si" : "no")); } static String lasciapassare() throws Exception { String aud = BASE + "/api-token"; // Il corpo si ricostruisce a ogni ripetizione: serve un'asserzione nuova (jti mai riusato). String r = chiama(() -> { try { return HttpRequest.newBuilder(URI.create(aud)).header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials&client_assertion_type=" + enc("urn:ietf:params:oauth:client-assertion-type:jwt-bearer") + "&client_assertion=" + asserzione(aud))); } catch (Exception e) { throw new RuntimeException(e); } }); return campo(r, "access_token"); } static String asserzione(String aud) throws Exception { String pem = Files.readString(Path.of(CHIAVE)); if (!pem.contains("BEGIN PRIVATE KEY")) throw new IllegalStateException("Serve un PEM PKCS#8: openssl pkcs8 -topk8 -nocrypt -in privata.pem -out privata-pkcs8.pem"); byte[] der = Base64.getMimeDecoder().decode(pem.replaceAll("-----[A-Z ]+-----", "").replaceAll("\\s", "")); PrivateKey chiave; try { chiave = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(der)); } catch (Exception e) { chiave = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(der)); } boolean ecdsa = chiave instanceof ECPrivateKey; String alg = ecdsa ? "ES256" : "RS256"; long ora = System.currentTimeMillis() / 1000; String testa = b64u(("{\"alg\":\"" + alg + "\",\"kid\":\"" + KID + "\",\"typ\":\"JWT\"}").getBytes(StandardCharsets.UTF_8)); String corpo = b64u(("{\"iss\":\"" + CLIENTE + "\",\"sub\":\"" + CLIENTE + "\",\"aud\":\"" + aud + "\",\"iat\":" + ora + ",\"exp\":" + (ora + 120) + ",\"jti\":\"" + UUID.randomUUID() + "\"}").getBytes(StandardCharsets.UTF_8)); Signature s = Signature.getInstance(ecdsa ? "SHA256withECDSA" : "SHA256withRSA"); s.initSign(chiave); s.update((testa + "." + corpo).getBytes(StandardCharsets.US_ASCII)); byte[] firma = s.sign(); if (ecdsa) firma = derInJose(firma); return testa + "." + corpo + "." + b64u(firma); } // Java firma ECDSA in DER; JWT (ES256) vuole r||s di 32 byte ciascuno. static byte[] derInJose(byte[] der) { int i = 2 + ((der[1] & 0x80) != 0 ? (der[1] & 0x7f) : 0); int lr = der[i + 1]; byte[] r = java.util.Arrays.copyOfRange(der, i + 2, i + 2 + lr); i = i + 2 + lr; int ls = der[i + 1]; byte[] s = java.util.Arrays.copyOfRange(der, i + 2, i + 2 + ls); byte[] out = new byte[64]; System.arraycopy(r, Math.max(0, r.length - 32), out, 32 - Math.min(32, r.length), Math.min(32, r.length)); System.arraycopy(s, Math.max(0, s.length - 32), out, 64 - Math.min(32, s.length), Math.min(32, s.length)); return out; } // Ripetizioni: 429 rispetta Retry-After; 5xx ed errori di rete con attese crescenti (1, 2, 4, 8 s). static String chiama(HttpRequest.Builder b) throws Exception { return chiama(() -> b); } static String chiama(java.util.function.Supplier fornitore) throws Exception { for (int i = 0; ; i++) { HttpRequest req = fornitore.get().build(); HttpResponse r; try { r = HTTP.send(req, HttpResponse.BodyHandlers.ofString()); } catch (java.io.IOException e) { if (i >= 4) throw e; Thread.sleep((1L << i) * 1000); continue; } if ((r.statusCode() == 429 || r.statusCode() >= 500) && i < 4) { long attesa = r.headers().firstValue("Retry-After").map(Long::parseLong).orElse(1L << i); Thread.sleep(attesa * 1000); continue; } String id = campo(r.body(), "id_richiesta"); System.out.println(req.method() + " " + req.uri().toString().replace(BASE, "") + " -> " + r.statusCode() + (id != null ? " (id_richiesta " + id + ")" : "")); if (r.statusCode() >= 400) System.out.println(r.body()); return r.body(); } } static String campo(String json, String nome) { Matcher m = Pattern.compile("\"" + nome + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json == null ? "" : json); return m.find() ? m.group(1) : null; } }