ModIUtilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.protocol.modipa.utils;

  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Properties;

  25. import javax.xml.namespace.QName;
  26. import javax.xml.soap.SOAPHeader;
  27. import javax.xml.soap.SOAPHeaderElement;

  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.config.CanaliConfigurazione;
  30. import org.openspcoop2.core.config.PortaApplicativa;
  31. import org.openspcoop2.core.config.PortaDelegata;
  32. import org.openspcoop2.core.config.constants.RuoloContesto;
  33. import org.openspcoop2.core.id.IDAccordo;
  34. import org.openspcoop2.core.id.IDPortTypeAzione;
  35. import org.openspcoop2.core.id.IDPortaApplicativa;
  36. import org.openspcoop2.core.id.IDPortaDelegata;
  37. import org.openspcoop2.core.id.IDResource;
  38. import org.openspcoop2.core.id.IDServizio;
  39. import org.openspcoop2.core.id.IDSoggetto;
  40. import org.openspcoop2.core.mapping.MappingErogazionePortaApplicativa;
  41. import org.openspcoop2.core.mapping.MappingFruizionePortaDelegata;
  42. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  43. import org.openspcoop2.core.registry.Resource;
  44. import org.openspcoop2.core.registry.constants.ServiceBinding;
  45. import org.openspcoop2.core.registry.driver.IDAccordoFactory;
  46. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  47. import org.openspcoop2.message.constants.MessageType;
  48. import org.openspcoop2.message.soap.SoapUtils;
  49. import org.openspcoop2.message.xml.MessageXMLUtils;
  50. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  51. import org.openspcoop2.pdd.config.UrlInvocazioneAPI;
  52. import org.openspcoop2.pdd.core.autorizzazione.canali.CanaliUtils;
  53. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  54. import org.openspcoop2.protocol.engine.SecurityTokenUtilities;
  55. import org.openspcoop2.protocol.engine.utils.NamingUtils;
  56. import org.openspcoop2.protocol.modipa.config.ModIProperties;
  57. import org.openspcoop2.protocol.modipa.constants.ModICostanti;
  58. import org.openspcoop2.protocol.sdk.Busta;
  59. import org.openspcoop2.protocol.sdk.Context;
  60. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  61. import org.openspcoop2.protocol.sdk.ProtocolException;
  62. import org.openspcoop2.protocol.sdk.SecurityToken;
  63. import org.openspcoop2.protocol.sdk.properties.ProtocolProperties;
  64. import org.openspcoop2.protocol.sdk.properties.ProtocolPropertiesUtils;
  65. import org.openspcoop2.protocol.sdk.registry.ProtocolFiltroRicercaPortTypeAzioni;
  66. import org.openspcoop2.protocol.sdk.registry.ProtocolFiltroRicercaRisorse;
  67. import org.openspcoop2.protocol.sdk.registry.ProtocolFiltroRicercaServizi;
  68. import org.openspcoop2.protocol.sdk.registry.IConfigIntegrationReader;
  69. import org.openspcoop2.protocol.sdk.registry.IRegistryReader;
  70. import org.openspcoop2.protocol.sdk.registry.RegistryNotFound;
  71. import org.openspcoop2.protocol.sdk.state.IState;
  72. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  73. import org.openspcoop2.utils.MapKey;
  74. import org.openspcoop2.utils.Utilities;
  75. import org.openspcoop2.utils.UtilsMultiException;
  76. import org.openspcoop2.utils.regexp.RegularExpressionEngine;
  77. import org.slf4j.Logger;
  78. import org.w3c.dom.Element;
  79. import org.w3c.dom.Node;
  80. import org.w3c.dom.NodeList;

  81. /**
  82.  * ModIImbustamentoUtilities
  83.  *
  84.  * @author Poli Andrea (apoli@link.it)
  85.  * @author $Author$
  86.  * @version $Rev$, $Date$
  87.  */
  88. public class ModIUtilities {
  89.    
  90.     private ModIUtilities() {}

  91.     private static void logError(Logger log, String msg) {
  92.         log.error(msg);
  93.     }
  94.    
  95.     public static final boolean REMOVE = true;
  96.     public static boolean exists(Properties p, String key) {
  97.         return get(p, key, false) !=null;
  98.     }
  99.     public static String get(Properties p, String key, boolean remove) {
  100.         if(p==null || p.isEmpty()) {
  101.             return null;
  102.         }
  103.         for (Object oKeyP : p.keySet()) {
  104.             if(oKeyP instanceof String) {
  105.                 String keyP = (String) oKeyP;
  106.                 if(keyP.equalsIgnoreCase(key)) {
  107.                     String s = p.getProperty(keyP);
  108.                     if(remove) {
  109.                         p.remove(keyP);
  110.                     }
  111.                     return s;
  112.                 }
  113.             }
  114.         }
  115.         return null;
  116.     }
  117.     public static void remove(Properties p, String key) {
  118.         if(p==null || p.isEmpty()) {
  119.             return;
  120.         }
  121.         for (Object oKeyP : p.keySet()) {
  122.             if(oKeyP instanceof String) {
  123.                 String keyP = (String) oKeyP;
  124.                 if(keyP.equalsIgnoreCase(key)) {
  125.                     p.remove(keyP);
  126.                     break;
  127.                 }
  128.             }
  129.         }
  130.     }
  131.    
  132.     public static List<String> getArrayStringAsList(String v, boolean deleteQuote) {
  133.         List<String> l = null;
  134.         if(v!=null && v.startsWith("[") && v.endsWith("]") && v.length()>2) {
  135.             String newValue = v.substring(1, v.length()-1);
  136.             return ModIUtilities.getAsList(newValue, deleteQuote);
  137.         }
  138.         return l;
  139.     }
  140.     public static List<String> getAsList(String values, boolean deleteQuote){
  141.         List<String> l = new ArrayList<>();
  142.         if(values.contains(",")) {
  143.             String [] tmp = values.split(",");
  144.             convertAsListValue(l, tmp, deleteQuote);
  145.         }
  146.         else {
  147.             String v = values;
  148.             if(deleteQuote && v.startsWith("\"") && v.endsWith("\"") && v.length()>2) {
  149.                 v = v.substring(1, v.length()-1);
  150.             }
  151.             l.add(v);
  152.         }
  153.         return l;
  154.     }
  155.     private static void convertAsListValue(List<String> l, String [] tmp, boolean deleteQuote) {
  156.         if(tmp!=null && tmp.length>0) {
  157.             for (String v : tmp) {
  158.                 v = v.trim();
  159.                 if(deleteQuote && v.startsWith("\"") && v.endsWith("\"") && v.length()>2) {
  160.                     v = v.substring(1, v.length()-1);
  161.                 }
  162.                 if(StringUtils.isNotEmpty(v)) {
  163.                     l.add(v);
  164.                 }
  165.             }
  166.         }
  167.     }
  168.    
  169.     public static String extractCorrelationIdFromLocation(String resourcePath, String location, boolean throwException, Logger log) throws ProtocolException {
  170.         if(resourcePath==null) {
  171.             throw new ProtocolException("Resource path della risorsa correlata non trovato");
  172.         }
  173.        
  174.         String [] rSplit = resourcePath.split("/");
  175.         int lastDynamicPosition = -1;
  176.         for (String r : rSplit) {
  177.             if(r.startsWith("{")) {
  178.                 lastDynamicPosition++;
  179.             }
  180.         }
  181.        
  182.         int lastDynamicPos = 0;
  183.         StringBuilder sb = new StringBuilder();
  184.         for (String r : rSplit) {
  185.             if(r==null || "".equals(r)) {
  186.                 continue;
  187.             }
  188.             sb.append("/+");
  189.             if(r.startsWith("{")) {
  190.                 if(lastDynamicPos == lastDynamicPosition) {
  191.                     sb.append("([^/]+)");
  192.                 }
  193.                 else {
  194.                     sb.append(".*");
  195.                 }
  196.                 lastDynamicPos++;
  197.             }
  198.             else {
  199.                 sb.append(r);
  200.             }
  201.         }
  202.         sb.append("/?");
  203.         String pattern = sb.toString();
  204.        
  205.         try {
  206.             return RegularExpressionEngine.getStringFindPattern(location, pattern);
  207.         }catch(Exception e) {
  208.             logError(log,"Estrazione Id Correlazione dalla Location '"+location+"' non riuscita (resourcePath: "+resourcePath+") (pattern: "+pattern+")");
  209.             if(throwException) {
  210.                 throw new ProtocolException(e.getMessage(),e);
  211.             }
  212.         }
  213.        
  214.         return null;
  215.     }
  216.    
  217.     public static String extractCorrelationId(String location, AccordoServizioParteComune apiContenenteRisorsa,
  218.             String azione, String asyncInteractionRole, Logger log) throws ProtocolException {
  219.         if(location!=null) {
  220.             location = location.trim();
  221.            
  222.             String resourcePath = null;
  223.             if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  224.                 for (Resource r : apiContenenteRisorsa.getResourceList()) {
  225.                     if(r.getNome().equals(azione)) {
  226.                         continue;
  227.                     }
  228.                     String ruolo = ProtocolPropertiesUtils.getOptionalStringValuePropertyRegistry(r.getProtocolPropertyList(),
  229.                             ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO);
  230.                     if(ruolo!=null && ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(ruolo)) {
  231.                         String actionCorrelata = ProtocolPropertiesUtils.getOptionalStringValuePropertyRegistry(r.getProtocolPropertyList(),
  232.                                 ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA);  
  233.                         if(actionCorrelata!=null && actionCorrelata.equals(azione)) {
  234.                             resourcePath = r.getPath();
  235.                             break;
  236.                         }
  237.                     }
  238.                    
  239.                 }
  240.             }
  241.             else if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(asyncInteractionRole)) {
  242.                
  243.                 String azioneRichiesta = null;
  244.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(asyncInteractionRole)) {
  245.                     Resource rRichiestaStato = null;
  246.                     for (Resource r : apiContenenteRisorsa.getResourceList()) {
  247.                         if(r.getNome().equals(azione)) {
  248.                             rRichiestaStato = r;
  249.                             break;
  250.                         }
  251.                     }
  252.                     if(rRichiestaStato==null) {
  253.                         throw new ProtocolException("Risorsa con ruolo 'Richiesta Stato' non trovata");
  254.                     }
  255.                     azioneRichiesta = ProtocolPropertiesUtils.getRequiredStringValuePropertyRegistry(rRichiestaStato.getProtocolPropertyList(),
  256.                             ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA);  
  257.                 }
  258.                
  259.                 for (Resource r : apiContenenteRisorsa.getResourceList()) {
  260.                     if(!r.getNome().equals(azioneRichiesta)) {
  261.                         String ruolo = ProtocolPropertiesUtils.getOptionalStringValuePropertyRegistry(r.getProtocolPropertyList(),
  262.                                 ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO);
  263.                         if(ruolo!=null && ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA.equals(ruolo)) {
  264.                             String actionCorrelata = ProtocolPropertiesUtils.getOptionalStringValuePropertyRegistry(r.getProtocolPropertyList(),
  265.                                     ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA);  
  266.                             if(actionCorrelata!=null && actionCorrelata.equals(azioneRichiesta)) {
  267.                                 resourcePath = r.getPath();
  268.                                 break;
  269.                             }
  270.                         }
  271.                     }
  272.                 }
  273.             }
  274.              
  275.             if(resourcePath==null) {
  276.                 throw new ProtocolException("Resource path della risorsa correlata non trovato");
  277.             }
  278.             return ModIUtilities.extractCorrelationIdFromLocation(resourcePath, location, false, log);
  279.                        
  280.         }
  281.         return null;
  282.     }
  283.    
  284.     public static String getReplyToErogazione(IDSoggetto idSoggettoErogatoreServizioCorrelato,
  285.             AccordoServizioParteComune aspc, String portType, String azione,
  286.             IRegistryReader registryReader, IConfigIntegrationReader configIntegrationReader,
  287.             IProtocolFactory<?> protocolFactory, IState state, RequestInfo requestInfo) throws ProtocolException {
  288.         return getReplyTo(false, null, idSoggettoErogatoreServizioCorrelato,
  289.                 aspc, portType, azione,
  290.                 registryReader, configIntegrationReader,
  291.                 protocolFactory, state, requestInfo);
  292.     }
  293.     public static String getReplyToFruizione(IDSoggetto idSoggettoFrutore, IDSoggetto idSoggettoErogatoreServizioCorrelato,
  294.             AccordoServizioParteComune aspc, String portType, String azione,
  295.             IRegistryReader registryReader, IConfigIntegrationReader configIntegrationReader,
  296.             IProtocolFactory<?> protocolFactory, IState state, RequestInfo requestInfo) throws ProtocolException {
  297.         return getReplyTo(true, idSoggettoFrutore, idSoggettoErogatoreServizioCorrelato,
  298.                 aspc, portType, azione,
  299.                 registryReader, configIntegrationReader,
  300.                 protocolFactory, state, requestInfo);
  301.     }
  302.     private static String getReplyTo(boolean fruizione, IDSoggetto idSoggettoFrutore, IDSoggetto idSoggettoErogatoreServizioCorrelato,
  303.             AccordoServizioParteComune aspc, String portType, String azione,
  304.             IRegistryReader registryReader, IConfigIntegrationReader configIntegrationReader,
  305.             IProtocolFactory<?> protocolFactory, IState state, RequestInfo requestInfo) throws ProtocolException {
  306.        
  307.         try {
  308.        
  309.             if(configIntegrationReader!=null) {
  310.                 // nop
  311.             }
  312.            
  313.             String uriAPC = IDAccordoFactory.getInstance().getUriFromAccordo(aspc);
  314.             boolean rest = ServiceBinding.REST.equals(aspc.getServiceBinding());
  315.            
  316.             IDAccordo idAccordoRisposta = null;
  317.             String portTypeRisposta = null;
  318.            
  319.             if(rest) {
  320.                 ProtocolFiltroRicercaRisorse filtroRisorse = new ProtocolFiltroRicercaRisorse();
  321.                 filtroRisorse.setProtocolPropertiesRisorsa(new ProtocolProperties());
  322.                 filtroRisorse.getProtocolPropertiesRisorsa().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO,
  323.                         ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA);
  324.                 filtroRisorse.getProtocolPropertiesRisorsa().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_API_RICHIESTA_CORRELATA,
  325.                         uriAPC);
  326.                 filtroRisorse.getProtocolPropertiesRisorsa().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA,
  327.                         azione);
  328.                 List<IDResource> l = null;
  329.                 try {
  330.                     l = registryReader.findIdResourceAccordo(filtroRisorse);
  331.                 }catch(RegistryNotFound notFound) {
  332.                     // ignore
  333.                 }
  334.                 if(l==null || l.isEmpty()) {
  335.                     throw new RegistryNotFound("Non รจ stata individuata alcun API contenente una risorsa correlata alla richiesta in corso");
  336.                 }
  337.                 if(l.size()>1) {
  338.                     throw new RegistryNotFound("Sono state individuate piรน di una risorsa contenente una correlazione verso la richiesta in corso: "+l);
  339.                 }
  340.                 IDResource idResource = l.get(0);
  341.                 idAccordoRisposta = idResource.getIdAccordo();
  342.             }
  343.             else {
  344.                 ProtocolFiltroRicercaPortTypeAzioni filtroPTAzioni = new ProtocolFiltroRicercaPortTypeAzioni();
  345.                 filtroPTAzioni.setProtocolPropertiesAzione(new ProtocolProperties());
  346.                 filtroPTAzioni.getProtocolPropertiesAzione().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO,
  347.                         ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA);
  348.                 filtroPTAzioni.getProtocolPropertiesAzione().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_API_RICHIESTA_CORRELATA,
  349.                         uriAPC);
  350.                 filtroPTAzioni.getProtocolPropertiesAzione().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_SERVIZIO_RICHIESTA_CORRELATA,
  351.                         portType);
  352.                 filtroPTAzioni.getProtocolPropertiesAzione().addProperty(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_AZIONE_RICHIESTA_CORRELATA,
  353.                         azione);
  354.                 List<IDPortTypeAzione> l = null;
  355.                 try {
  356.                     l = registryReader.findIdAzionePortType(filtroPTAzioni);
  357.                 }catch(RegistryNotFound notFound) {
  358.                 }
  359.                 if(l==null || l.isEmpty()) {
  360.                     throw new RegistryNotFound("Non รจ stata individuata alcun API contenente un'azione correlata alla richiesta in corso");
  361.                 }
  362.                 if(l.size()>1) {
  363.                     throw new RegistryNotFound("Sono state individuate piรน di un'azione contenente una correlazione verso la richiesta in corso: "+l);
  364.                 }
  365.                 IDPortTypeAzione idPTAzione = l.get(0);
  366.                 idAccordoRisposta = idPTAzione.getIdPortType().getIdAccordo();
  367.                 portTypeRisposta = idPTAzione.getIdPortType().getNome();
  368.             }
  369.                
  370.             ProtocolFiltroRicercaServizi filtroServizi = new ProtocolFiltroRicercaServizi();
  371.             filtroServizi.setIdAccordoServizioParteComune(idAccordoRisposta);
  372.             filtroServizi.setSoggettoErogatore(idSoggettoErogatoreServizioCorrelato);
  373.             if(!rest) {
  374.                 filtroServizi.setPortType(portTypeRisposta);
  375.             }
  376.             List<IDServizio> lIdServizio = null;
  377.             try {
  378.                 lIdServizio = registryReader.findIdAccordiServizioParteSpecifica(filtroServizi);
  379.             }catch(RegistryNotFound notFound) {
  380.             }
  381.             if(lIdServizio==null || lIdServizio.isEmpty()) {
  382.                 if(fruizione) {
  383.                     throw new RegistryNotFound("Non รจ stata individuata alcuna fruzione verso l'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta)+
  384.                             " erogata dal soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato));
  385.                 }
  386.                 else {
  387.                     throw new RegistryNotFound("Non รจ stata individuata alcun'erogazione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato)+
  388.                         " relativamente all'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta));
  389.                 }
  390.             }
  391.             if(lIdServizio.size()>1) {
  392.                 if(fruizione) {
  393.                     throw new RegistryNotFound("Sono state individuate piรน fruzioni verso l'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta)+
  394.                             " erogata dal soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato));
  395.                 }
  396.                 else {
  397.                     throw new RegistryNotFound("Sono state individuate piรน di un'erogazione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato)+
  398.                         " relativamente all'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta));
  399.                 }
  400.             }
  401.             IDServizio idServizioCorrelato = lIdServizio.get(0);
  402.            
  403.             if(fruizione) {
  404.                 List<MappingFruizionePortaDelegata> listMapping = ConfigurazionePdDManager.getInstance(state).getMappingFruizionePortaDelegataList(idSoggettoFrutore, idServizioCorrelato, requestInfo);
  405.                 if(listMapping==null) {
  406.                     throw new RegistryNotFound("(outbound empty) Non รจ stata individuata alcuna fruzione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoFrutore)+
  407.                             " verso l'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta)+
  408.                             " erogata dal soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato));
  409.                 }
  410.                 String nomePD = null;
  411.                 IDSoggetto proprietarioPD = null;
  412.                 for (MappingFruizionePortaDelegata mappingFruizionePortaDelegata : listMapping) {
  413.                     if(mappingFruizionePortaDelegata.isDefault()) {
  414.                         nomePD = mappingFruizionePortaDelegata.getIdPortaDelegata().getNome();
  415.                         proprietarioPD = idSoggettoFrutore;
  416.                     }
  417.                 }
  418.                 if(nomePD==null) {
  419.                     throw new RegistryNotFound("(outbound) Non รจ stata individuata alcuna fruzione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoFrutore)+
  420.                             " verso l'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta)+
  421.                             " erogata dal soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato));
  422.                 }
  423.                 return getUrlInvocazione(protocolFactory, state, requestInfo,
  424.                         rest, aspc, RuoloContesto.PORTA_DELEGATA, nomePD, proprietarioPD);
  425.             }
  426.             else {
  427.                 List<MappingErogazionePortaApplicativa> listMapping = ConfigurazionePdDManager.getInstance(state).getMappingErogazionePortaApplicativaList(idServizioCorrelato, requestInfo);
  428.                 if(listMapping==null) {
  429.                     throw new RegistryNotFound("(inbound empty) Non รจ stata individuata alcun'erogazione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato)+
  430.                             " relativamente all'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta));
  431.                 }
  432.                 String nomePA = null;
  433.                 IDSoggetto proprietarioPA = null;
  434.                 for (MappingErogazionePortaApplicativa mappingErogazionePortaApplicativa : listMapping) {
  435.                     if(mappingErogazionePortaApplicativa.isDefault()) {
  436.                         nomePA = mappingErogazionePortaApplicativa.getIdPortaApplicativa().getNome();
  437.                         proprietarioPA = idServizioCorrelato.getSoggettoErogatore();
  438.                     }
  439.                 }
  440.                 if(nomePA==null) {
  441.                     throw new RegistryNotFound("(inbound) Non รจ stata individuata alcun'erogazione da parte del soggetto "+NamingUtils.getLabelSoggetto(idSoggettoErogatoreServizioCorrelato)+
  442.                             " relativamente all'API "+NamingUtils.getLabelAccordoServizioParteComune(idAccordoRisposta));
  443.                 }
  444.                 return getUrlInvocazione(protocolFactory, state, requestInfo,
  445.                         rest, aspc, RuoloContesto.PORTA_APPLICATIVA, nomePA, proprietarioPA);
  446.             }
  447.         }catch(Exception e) {
  448.             throw new ProtocolException(e.getMessage(),e);
  449.         }
  450.     }
  451.    
  452.    
  453.     public static String getUrlInvocazione(IProtocolFactory<?> protocolFactory, IState state, RequestInfo requestInfo,
  454.             boolean rest, AccordoServizioParteComune aspc, RuoloContesto ruoloContesto, String nomePorta, IDSoggetto proprietarioPorta) throws ProtocolException {
  455.         try {
  456.             List<String> tags = new ArrayList<>();
  457.             if(aspc!=null && aspc.getGruppi()!=null && aspc.getGruppi().sizeGruppoList()>0) {
  458.                 for (int i = 0; i < aspc.getGruppi().sizeGruppoList(); i++) {
  459.                     tags.add(aspc.getGruppi().getGruppo(i).getNome());
  460.                 }
  461.             }
  462.            
  463.             IConfigIntegrationReader configReader = protocolFactory.getCachedConfigIntegrationReader(state, requestInfo);
  464.             CanaliConfigurazione canaliConfigurazione = configReader.getCanaliConfigurazione();
  465.             String canaleApi = null;
  466.             if(aspc!=null) {
  467.                 canaleApi = aspc.getCanale();
  468.             }
  469.             String canalePorta = null;
  470.             if(nomePorta!=null) {
  471.                 if(RuoloContesto.PORTA_APPLICATIVA.equals(ruoloContesto)) {
  472.                     try {
  473.                         IDPortaApplicativa idPA = new IDPortaApplicativa();
  474.                         idPA.setNome(nomePorta);
  475.                         PortaApplicativa pa = configReader.getPortaApplicativa(idPA);
  476.                         canalePorta = pa.getNome();
  477.                     }catch(Exception t) {
  478.                         // ignore
  479.                     }
  480.                 }
  481.                 else {
  482.                     try {
  483.                         IDPortaDelegata idPD = new IDPortaDelegata();
  484.                         idPD.setNome(nomePorta);
  485.                         PortaDelegata pd = configReader.getPortaDelegata(idPD);
  486.                         canalePorta = pd.getNome();
  487.                     }catch(Exception t) {
  488.                         // ignore
  489.                     }
  490.                 }
  491.             }
  492.             String canale = CanaliUtils.getCanale(canaliConfigurazione, canaleApi, canalePorta);
  493.            
  494.             UrlInvocazioneAPI urlInvocazioneApi = ConfigurazionePdDManager.getInstance().getConfigurazioneUrlInvocazione(protocolFactory,
  495.                     ruoloContesto,
  496.                     rest ? org.openspcoop2.message.constants.ServiceBinding.REST : org.openspcoop2.message.constants.ServiceBinding.SOAP,
  497.                     nomePorta,
  498.                     proprietarioPorta,
  499.                     tags, canale,
  500.                     requestInfo);        
  501.             String prefixGatewayUrl = urlInvocazioneApi.getBaseUrl();
  502.             String contesto = urlInvocazioneApi.getContext();
  503.             return Utilities.buildUrl(prefixGatewayUrl, contesto);
  504.         }catch(Exception e) {
  505.             throw new ProtocolException(e.getMessage(),e);
  506.         }
  507.     }
  508.    
  509.     public static String getSOAPHeaderReplyToValue(OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione) throws ProtocolException {
  510.         boolean useSoapReader = true; // interessa solo il valore
  511.         SOAPHeaderElement hdrElement = getSOAPHeaderReplyTo(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione);
  512.         return hdrElement!=null ? hdrElement.getValue() : null;
  513.     }
  514.     public static SOAPHeaderElement getSOAPHeaderReplyTo(boolean useSoapReader, OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione) throws ProtocolException {
  515.         try {
  516.             ModIProperties modIProperties = ModIProperties.getInstance();
  517.    
  518.             SOAPInfo soapInfo = new SOAPInfo();
  519.             boolean readRootElementInfo = modIProperties.useSoapBodyReplyToNamespace();
  520.             soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  521.                     false, true, readRootElementInfo);
  522.            
  523.             MessageType messageType = soapMessage.getMessageType();
  524.             SOAPHeader header = soapInfo.getHeader();
  525.             String namespace = readRootElementInfo ? soapInfo.getRootElementNamespace() : modIProperties.getSoapReplyToNamespace();
  526.            
  527.             return getSOAPHeaderElement(messageType, header, modIProperties.getSoapReplyToName(),
  528.                     namespace,
  529.                     modIProperties.getSoapReplyToActor());
  530.         }catch(Exception e) {
  531.             throw new ProtocolException(e.getMessage(),e);
  532.         }
  533.     }
  534.     public static String getSOAPHeaderCorrelationIdValue(OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione) throws ProtocolException {
  535.         boolean useSoapReader = true; // interessa solo il valore
  536.         SOAPHeaderElement hdrElement = getSOAPHeaderCorrelationId(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione);
  537.         return hdrElement!=null ? hdrElement.getValue() : null;
  538.     }
  539.     public static SOAPHeaderElement getSOAPHeaderCorrelationId(boolean useSoapReader, OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione) throws ProtocolException {
  540.         try {
  541.        
  542.             ModIProperties modIProperties = ModIProperties.getInstance();
  543.            
  544.             SOAPInfo soapInfo = new SOAPInfo();
  545.             boolean readRootElementInfo = modIProperties.useSoapBodyCorrelationIdNamespace();
  546.             soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  547.                     false, true, readRootElementInfo);
  548.            
  549.             MessageType messageType = soapMessage.getMessageType();
  550.             SOAPHeader header = soapInfo.getHeader();
  551.             String namespace = readRootElementInfo ? soapInfo.getRootElementNamespace() : modIProperties.getSoapCorrelationIdNamespace();
  552.            
  553.             return getSOAPHeaderElement(messageType, header, modIProperties.getSoapCorrelationIdName(),
  554.                     namespace,
  555.                     modIProperties.getSoapCorrelationIdActor());
  556.            
  557.         }catch(Exception e) {
  558.             throw new ProtocolException(e.getMessage(),e);
  559.         }
  560.     }
  561.    
  562.     public static SOAPHeaderElement getSOAPHeaderRequestDigest(boolean useSoapReader, OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione) throws ProtocolException {
  563.         try {
  564.        
  565.             ModIProperties modIProperties = ModIProperties.getInstance();
  566.            
  567.             SOAPInfo soapInfo = new SOAPInfo();
  568.             boolean readRootElementInfo = modIProperties.useSoapBodyRequestDigestNamespace();
  569.             soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  570.                     false, true, readRootElementInfo);
  571.            
  572.             MessageType messageType = soapMessage.getMessageType();
  573.             SOAPHeader header = soapInfo.getHeader();
  574.             String namespace = readRootElementInfo ? soapInfo.getRootElementNamespace() : modIProperties.getSoapRequestDigestNamespace();
  575.            
  576.             return getSOAPHeaderElement(messageType, header, modIProperties.getSoapRequestDigestName(),
  577.                     namespace,
  578.                     modIProperties.getSoapRequestDigestActor());
  579.            
  580.         }catch(Exception e) {
  581.             throw new ProtocolException(e.getMessage(),e);
  582.         }
  583.     }
  584.    
  585.     public static SOAPHeaderElement getSOAPHeaderElement(MessageType messageType, SOAPHeader header, String localName, String namespace, String actor) throws ProtocolException {
  586.    
  587.         try {
  588.        
  589.             if(header==null){
  590.                 return null;
  591.             }
  592.             java.util.Iterator<?> it = header.examineAllHeaderElements();
  593.             while( it.hasNext()  ){
  594.                 // Test Header Element
  595.                 SOAPHeaderElement headerElementCheck = (SOAPHeaderElement) it.next();
  596.                
  597.                 if(!namespace.equals(headerElementCheck.getNamespaceURI())) {
  598.                     continue;
  599.                 }
  600.                 if(!localName.equals(headerElementCheck.getLocalName())) {
  601.                     continue;
  602.                 }
  603.                
  604.                 //Controllo Actor
  605.                 String actorCheck = SoapUtils.getSoapActor(headerElementCheck, messageType);
  606.                 if(actor==null) {
  607.                     if(actorCheck==null) {
  608.                         return headerElementCheck;
  609.                     }
  610.                 }
  611.                 else {
  612.                     if( actor.equals(actorCheck) ){
  613.                         return headerElementCheck;
  614.                     }
  615.                 }
  616.             }
  617.            
  618.             return null;
  619.            
  620.         }catch(Exception e) {
  621.             throw new ProtocolException(e.getMessage(),e);
  622.         }
  623.     }
  624.    
  625.     public static void addSOAPHeaderReplyTo(OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione, String value) throws ProtocolException {
  626.         try {
  627.             ModIProperties modIProperties = ModIProperties.getInstance();
  628.            
  629.             boolean useSoapReader = true; // vengono recuperati solamente i prefissi e namespace.
  630.             SOAPInfo soapInfo = new SOAPInfo();
  631.             boolean readRootElementInfo = modIProperties.useSoapBodyReplyToNamespace();
  632.             if(readRootElementInfo) {
  633.                 soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  634.                         false, false, readRootElementInfo);
  635.             }
  636.            
  637.             addSOAPHeaderElement(soapMessage, modIProperties.getSoapReplyToName(),
  638.                     modIProperties.useSoapBodyReplyToNamespace() ? soapInfo.getRootElementPrefix() : modIProperties.getSoapReplyToPrefix(),
  639.                     modIProperties.useSoapBodyReplyToNamespace() ? soapInfo.getRootElementNamespace() : modIProperties.getSoapReplyToNamespace(),
  640.                     modIProperties.getSoapReplyToActor(),
  641.                     modIProperties.isSoapReplyToMustUnderstand(),
  642.                     value);
  643.         }catch(Exception e) {
  644.             throw new ProtocolException(e.getMessage(),e);
  645.         }
  646.     }
  647.     public static void addSOAPHeaderCorrelationId(OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione, String value) throws ProtocolException {
  648.         try {
  649.             ModIProperties modIProperties = ModIProperties.getInstance();
  650.            
  651.             boolean useSoapReader = true; // vengono recuperati solamente i prefissi e namespace.
  652.             SOAPInfo soapInfo = new SOAPInfo();
  653.             boolean readRootElementInfo = modIProperties.useSoapBodyCorrelationIdNamespace();
  654.             if(readRootElementInfo) {
  655.                 soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  656.                         false, false, readRootElementInfo);
  657.             }
  658.            
  659.             addSOAPHeaderElement(soapMessage, modIProperties.getSoapCorrelationIdName(),
  660.                     modIProperties.useSoapBodyCorrelationIdNamespace() ? soapInfo.getRootElementPrefix() : modIProperties.getSoapCorrelationIdPrefix(),
  661.                     modIProperties.useSoapBodyCorrelationIdNamespace() ? soapInfo.getRootElementNamespace() : modIProperties.getSoapCorrelationIdNamespace(),
  662.                     modIProperties.getSoapCorrelationIdActor(),
  663.                     modIProperties.isSoapCorrelationIdMustUnderstand(),
  664.                     value);
  665.         }catch(Exception e) {
  666.             throw new ProtocolException(e.getMessage(),e);
  667.         }
  668.     }
  669.    
  670.     public static SOAPHeaderElement addSOAPHeaderRequestDigest(OpenSPCoop2SoapMessage soapMessage, boolean bufferMessageReadOnly, String idTransazione, NodeList value) throws ProtocolException {
  671.         try {
  672.             ModIProperties modIProperties = ModIProperties.getInstance();
  673.            
  674.             boolean useSoapReader = true; // vengono recuperati solamente i prefissi e namespace.
  675.             SOAPInfo soapInfo = new SOAPInfo();
  676.             boolean readRootElementInfo = modIProperties.useSoapBodyRequestDigestNamespace();
  677.             if(readRootElementInfo) {
  678.                 soapInfo.read(useSoapReader, soapMessage, bufferMessageReadOnly, idTransazione,
  679.                         false, false, readRootElementInfo);
  680.             }
  681.            
  682.             return addSOAPHeaderElement(soapMessage, modIProperties.getSoapRequestDigestName(),
  683.                     modIProperties.useSoapBodyRequestDigestNamespace() ? soapInfo.getRootElementPrefix() : modIProperties.getSoapRequestDigestPrefix(),
  684.                     modIProperties.useSoapBodyRequestDigestNamespace() ? soapInfo.getRootElementNamespace() : modIProperties.getSoapRequestDigestNamespace(),
  685.                     modIProperties.getSoapRequestDigestActor(),
  686.                     modIProperties.isSoapRequestDigestMustUnderstand(),
  687.                     value);
  688.         }catch(Exception e) {
  689.             throw new ProtocolException(e.getMessage(),e);
  690.         }
  691.     }
  692.    
  693.     public static SOAPHeaderElement addSOAPHeaderElement(OpenSPCoop2SoapMessage msg, String localName, String prefix, String namespace, String actor, boolean mustUnderstand, Object value) throws ProtocolException {
  694.        
  695.         try {
  696.        
  697.             // se gia esiste aggiorno il valore
  698.             SOAPHeaderElement hdrElement = getSOAPHeaderElement(msg.getMessageType(), msg.getSOAPHeader(), localName, namespace, actor);
  699.            
  700.             if(hdrElement==null) {
  701.                 SOAPHeader header = msg.getSOAPHeader();
  702.                 if(header==null){
  703.                     header = msg.getSOAPPart().getEnvelope().addHeader();
  704.                 }
  705.                 hdrElement = msg.newSOAPHeaderElement(header, new QName(namespace,localName,prefix));
  706.    
  707.                 if(actor!=null && !"".equals(actor)) {
  708.                     hdrElement.setActor(actor);
  709.                 }
  710.                 hdrElement.setMustUnderstand(mustUnderstand);
  711.                    
  712.                 msg.addHeaderElement(header, hdrElement);
  713.             }
  714.             if(value instanceof String) {
  715.                 hdrElement.setValue( (String) value);
  716.             }
  717.             else {
  718.                 NodeList nodeList = (NodeList) value;
  719.                 for (int i = 0; i < nodeList.getLength(); i++) {
  720.                     Node n = nodeList.item(i);
  721.                     byte[] ref = msg.getAsByte(n, false);
  722.                     Element element = MessageXMLUtils.getInstance(msg.getFactory()).newElement(ref);
  723.                     hdrElement.addChildElement(SoapUtils.getSoapFactory(msg.getFactory(), msg.getMessageType()).createElement(element));
  724.                 }
  725.             }
  726.        
  727.             return hdrElement;
  728.            
  729.         }catch(Exception e) {
  730.             throw new ProtocolException(e.getMessage(),e);
  731.         }
  732.     }
  733.    
  734.     public static String getDynamicValue(String tipoRisorsa, String template, Map<String, Object> dynamicMap, Context context) throws ProtocolException {
  735.         String valoreRisorsa = null;
  736.         try {
  737.             valoreRisorsa = DynamicUtils.convertDynamicPropertyValue(tipoRisorsa, template, dynamicMap, context);
  738.         }catch(Exception e) {
  739.             throw new ProtocolException("Conversione valore della risorsa ("+tipoRisorsa+") '"+template+"' non riuscita: "+e.getMessage(),e);
  740.         }
  741.         return valoreRisorsa;
  742.     }
  743.     public static String getDynamicValue(String tipoRisorsa, List<String> templates, Map<String, Object> dynamicMap, Context context) throws ProtocolException {
  744.         List<Exception> exceptions = new ArrayList<>();
  745.         for (String template : templates) {
  746.             try {
  747.                 String v = getDynamicValue(tipoRisorsa, template, dynamicMap, context);
  748.                 if(v!=null && !"".equals(v)) {
  749.                     return v;
  750.                 }
  751.             }catch(Exception t) {
  752.                 exceptions.add(t);
  753.             }
  754.         }
  755.         String errorMsg = "";
  756.         StringBuilder sb = new StringBuilder();
  757.         if(!exceptions.isEmpty()) {
  758.             for (Exception t : exceptions) {
  759.                 if(exceptions.size()>1) {
  760.                     sb.append("\n");
  761.                 }
  762.                 sb.append(t.getMessage());
  763.             }
  764.         }
  765.         if(sb.length()>0) {
  766.             errorMsg = ": "+ sb.toString();
  767.         }
  768.         UtilsMultiException multi = new UtilsMultiException("Non รจ stato possibile recuperare un valore da associare alla risorsa '"+tipoRisorsa+"'"+errorMsg, exceptions.toArray(new Throwable[1]));
  769.         throw new ProtocolException(multi.getMessage(), multi);
  770.     }
  771.    
  772.     public static void addHeaderProperty(Busta busta, String hdrName, String hdrValue) {
  773.         String pName = ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SIGNED_HEADER_PREFIX+hdrName;
  774.         String actualValue = busta.getProperty(pName);
  775.         if(actualValue!=null) {
  776.             for (int i = 2; i < 1000; i++) { // 1000 header con solito nome ?
  777.                 pName = ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SIGNED_HEADER_PREFIX+hdrName+ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SIGNED_HEADER_MULTIPLE_VALUE_SUFFIX+i;
  778.                 actualValue = busta.getProperty(pName);
  779.                 if(actualValue==null) {
  780.                     busta.addProperty(pName, hdrValue);
  781.                     break;
  782.                 }
  783.             }
  784.         }
  785.         else {
  786.             busta.addProperty(pName, hdrValue);
  787.         }
  788.     }
  789.    
  790.     private static final MapKey<String> DYNAMIC_MAP_REQUEST = org.openspcoop2.utils.Map.newMapKey("MODI_DYNAMIC_MAP_REQUEST");
  791.     public static void saveDynamicMapRequest(Context context, Map<String, Object> map){
  792.         if(context!=null && map!=null) {
  793.             context.addObject(DYNAMIC_MAP_REQUEST, map);
  794.         }
  795.     }
  796.     @SuppressWarnings("unchecked")
  797.     public static Map<String, Object> removeDynamicMapRequest(Context context){
  798.         Map<String, Object> map = null;
  799.         if(context!=null) {
  800.             Object o = context.removeObject(DYNAMIC_MAP_REQUEST);
  801.             if(o instanceof Map<?, ?>) {
  802.                 return (Map<String, Object>) o;
  803.             }
  804.         }
  805.         return map;
  806.     }
  807.    
  808.     public static SecurityToken newSecurityToken(Context context) {
  809.         return SecurityTokenUtilities.newSecurityToken(context);
  810.     }
  811.     public static SecurityToken readSecurityToken(Context context) {
  812.         return SecurityTokenUtilities.readSecurityToken(context);
  813.     }
  814. }