GestoreToken.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.pdd.core.token;

  21. import java.util.ArrayList;
  22. import java.util.Date;
  23. import java.util.Enumeration;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Properties;

  28. import javax.servlet.http.HttpServletRequest;

  29. import org.openspcoop2.core.commons.CoreException;
  30. import org.openspcoop2.core.config.AttributeAuthority;
  31. import org.openspcoop2.core.config.PortaApplicativa;
  32. import org.openspcoop2.core.config.PortaDelegata;
  33. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  34. import org.openspcoop2.core.constants.TipoPdD;
  35. import org.openspcoop2.core.id.IDGenericProperties;
  36. import org.openspcoop2.core.id.IDServizio;
  37. import org.openspcoop2.core.id.IDSoggetto;
  38. import org.openspcoop2.core.mvc.properties.provider.ProviderException;
  39. import org.openspcoop2.core.mvc.properties.provider.ProviderValidationException;
  40. import org.openspcoop2.core.registry.driver.IDServizioFactory;
  41. import org.openspcoop2.message.OpenSPCoop2Message;
  42. import org.openspcoop2.message.utils.WWWAuthenticateErrorCode;
  43. import org.openspcoop2.message.utils.WWWAuthenticateGenerator;
  44. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  45. import org.openspcoop2.pdd.config.ConfigurazionePdDReader;
  46. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  47. import org.openspcoop2.pdd.core.PdDContext;
  48. import org.openspcoop2.pdd.core.connettori.ConnettoreBaseHTTP;
  49. import org.openspcoop2.pdd.core.connettori.ConnettoreMsg;
  50. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  51. import org.openspcoop2.pdd.core.token.attribute_authority.AttributeAuthorityDynamicParameters;
  52. import org.openspcoop2.pdd.core.token.attribute_authority.AttributeAuthorityProvider;
  53. import org.openspcoop2.pdd.core.token.attribute_authority.EsitoRecuperoAttributi;
  54. import org.openspcoop2.pdd.core.token.attribute_authority.InformazioniAttributi;
  55. import org.openspcoop2.pdd.core.token.attribute_authority.PolicyAttributeAuthority;
  56. import org.openspcoop2.pdd.core.token.attribute_authority.pa.DatiInvocazionePortaApplicativa;
  57. import org.openspcoop2.pdd.core.token.attribute_authority.pd.DatiInvocazionePortaDelegata;
  58. import org.openspcoop2.pdd.core.token.pa.EsitoPresenzaTokenPortaApplicativa;
  59. import org.openspcoop2.pdd.core.token.pd.EsitoPresenzaTokenPortaDelegata;
  60. import org.openspcoop2.pdd.core.transazioni.Transaction;
  61. import org.openspcoop2.pdd.core.transazioni.TransactionContext;
  62. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  63. import org.openspcoop2.pdd.services.connector.FormUrlEncodedHttpServletRequest;
  64. import org.openspcoop2.protocol.engine.SecurityTokenUtilities;
  65. import org.openspcoop2.protocol.sdk.Busta;
  66. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  67. import org.openspcoop2.protocol.sdk.SecurityToken;
  68. import org.openspcoop2.protocol.sdk.state.IState;
  69. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  70. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  71. import org.openspcoop2.security.message.jose.JOSEUtils;
  72. import org.openspcoop2.utils.SemaphoreLock;
  73. import org.openspcoop2.utils.UtilsException;
  74. import org.openspcoop2.utils.cache.Cache;
  75. import org.openspcoop2.utils.cache.CacheAlgorithm;
  76. import org.openspcoop2.utils.cache.CacheType;
  77. import org.openspcoop2.utils.cache.Constants;
  78. import org.openspcoop2.utils.date.DateManager;
  79. import org.openspcoop2.utils.date.DateUtils;
  80. import org.openspcoop2.utils.transport.TransportUtils;
  81. import org.openspcoop2.utils.transport.http.HttpConstants;
  82. import org.slf4j.Logger;

  83. /**    
  84.  * GestoreToken
  85.  *
  86.  * @author Poli Andrea (poli@link.it)
  87.  * @author $Author$
  88.  * @version $Rev$, $Date$
  89.  */
  90. public class GestoreToken {
  91.    
  92.     private GestoreToken() {}

  93.     public static final boolean PORTA_DELEGATA = true;
  94.     public static final boolean PORTA_APPLICATIVA = false;
  95.    
  96.     /** Chiave della cache per la gestione dei token  */
  97.     private static final String GESTIONE_TOKEN_CACHE_NAME = "token";
  98.     /** Chiave della cache per la gestione dei dati raccolti via attribute authority  */
  99.     private static final String ATTRIBUTE_AUTHORITY_CACHE_NAME = "attributeAuthority";
  100.     /** Cache */
  101.     private static Cache cacheGestioneToken = null;
  102.     private static Cache cacheAttributeAuthority = null;
  103.    
  104.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockDynamicDiscovery = new HashMap<>();
  105.     private static synchronized org.openspcoop2.utils.Semaphore initLockDynamicDiscovery(String nomePolicy){
  106.         org.openspcoop2.utils.Semaphore s = _lockDynamicDiscovery.get(nomePolicy);
  107.         if(s==null) {
  108.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneTokenDynamicDiscoveryLockPermits();
  109.             if(permits!=null && permits.intValue()>1) {
  110.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenDynamicDiscovery_"+nomePolicy, permits);
  111.             }
  112.             else {
  113.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenDynamicDiscovery_"+nomePolicy);
  114.             }
  115.             _lockDynamicDiscovery.put(nomePolicy, s);
  116.         }
  117.         return s;
  118.     }
  119.     private static org.openspcoop2.utils.Semaphore getLockDynamicDiscovery(String nomePolicy){
  120.         org.openspcoop2.utils.Semaphore s = _lockDynamicDiscovery.get(nomePolicy);
  121.         if(s==null) {
  122.             s = initLockDynamicDiscovery(nomePolicy);
  123.         }
  124.         return s;
  125.     }
  126.    
  127.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockJWT = new HashMap<>();
  128.     private static synchronized org.openspcoop2.utils.Semaphore initLockJWT(String nomePolicy){
  129.         org.openspcoop2.utils.Semaphore s = _lockJWT.get(nomePolicy);
  130.         if(s==null) {
  131.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneTokenValidazioneJWTLockPermits();
  132.             if(permits!=null && permits.intValue()>1) {
  133.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenValidazioneJWT_"+nomePolicy, permits);
  134.             }
  135.             else {
  136.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenValidazioneJWT_"+nomePolicy);
  137.             }
  138.             _lockJWT.put(nomePolicy, s);
  139.         }
  140.         return s;
  141.     }
  142.     private static org.openspcoop2.utils.Semaphore getLockJWT(String nomePolicy){
  143.         org.openspcoop2.utils.Semaphore s = _lockJWT.get(nomePolicy);
  144.         if(s==null) {
  145.             s = initLockJWT(nomePolicy);
  146.         }
  147.         return s;
  148.     }
  149.    
  150.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockIntrospection = new HashMap<>();
  151.     private static synchronized org.openspcoop2.utils.Semaphore initLockIntrospection(String nomePolicy){
  152.         org.openspcoop2.utils.Semaphore s = _lockIntrospection.get(nomePolicy);
  153.         if(s==null) {
  154.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneTokenIntrospectionLockPermits();
  155.             if(permits!=null && permits.intValue()>1) {
  156.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenIntrospection_"+nomePolicy, permits);
  157.             }
  158.             else {
  159.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenIntrospection_"+nomePolicy);
  160.             }
  161.             _lockIntrospection.put(nomePolicy, s);
  162.         }
  163.         return s;
  164.     }
  165.     private static org.openspcoop2.utils.Semaphore getLockIntrospection(String nomePolicy){
  166.         org.openspcoop2.utils.Semaphore s = _lockIntrospection.get(nomePolicy);
  167.         if(s==null) {
  168.             s = initLockIntrospection(nomePolicy);
  169.         }
  170.         return s;
  171.     }
  172.    
  173.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockUserInfo = new HashMap<>();
  174.     private static synchronized org.openspcoop2.utils.Semaphore initLockUserInfo(String nomePolicy){
  175.         org.openspcoop2.utils.Semaphore s = _lockUserInfo.get(nomePolicy);
  176.         if(s==null) {
  177.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneTokenUserInfoLockPermits();
  178.             if(permits!=null && permits.intValue()>1) {
  179.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenUserInfo_"+nomePolicy, permits);
  180.             }
  181.             else {
  182.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenUserInfo_"+nomePolicy);
  183.             }
  184.             _lockUserInfo.put(nomePolicy, s);
  185.         }
  186.         return s;
  187.     }
  188.     private static org.openspcoop2.utils.Semaphore getLockUserInfo(String nomePolicy){
  189.         org.openspcoop2.utils.Semaphore s = _lockUserInfo.get(nomePolicy);
  190.         if(s==null) {
  191.             s = initLockUserInfo(nomePolicy);
  192.         }
  193.         return s;
  194.     }
  195.    
  196.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockNegoziazione = new HashMap<>();
  197.     private static synchronized org.openspcoop2.utils.Semaphore initLockNegoziazione(String nomePolicy){
  198.         org.openspcoop2.utils.Semaphore s = _lockNegoziazione.get(nomePolicy);
  199.         if(s==null) {
  200.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneRetrieveTokenLockPermits();
  201.             if(permits!=null && permits.intValue()>1) {
  202.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenNegoziazione_"+nomePolicy, permits);
  203.             }
  204.             else {
  205.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenNegoziazione_"+nomePolicy);
  206.             }
  207.             _lockNegoziazione.put(nomePolicy, s);
  208.         }
  209.         return s;
  210.     }
  211.     private static org.openspcoop2.utils.Semaphore getLockNegoziazione(String nomePolicy){
  212.         org.openspcoop2.utils.Semaphore s = _lockNegoziazione.get(nomePolicy);
  213.         if(s==null) {
  214.             s = initLockNegoziazione(nomePolicy);
  215.         }
  216.         return s;
  217.     }
  218.    
  219.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockAttributeAuthority = new HashMap<>();
  220.     private static synchronized org.openspcoop2.utils.Semaphore initLockAttributeAuthority(String nomePolicy){
  221.         org.openspcoop2.utils.Semaphore s = _lockAttributeAuthority.get(nomePolicy);
  222.         if(s==null) {
  223.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneAttributeAuthorityLockPermits();
  224.             if(permits!=null && permits.intValue()>1) {
  225.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenAttributeAuthority_"+nomePolicy, permits);
  226.             }
  227.             else {
  228.                 s = new org.openspcoop2.utils.Semaphore("GestoreTokenAttributeAuthority_"+nomePolicy);
  229.             }
  230.             _lockAttributeAuthority.put(nomePolicy, s);
  231.         }
  232.         return s;
  233.     }
  234.     private static org.openspcoop2.utils.Semaphore getLockAttributeAuthority(String nomePolicy){
  235.         org.openspcoop2.utils.Semaphore s = _lockAttributeAuthority.get(nomePolicy);
  236.         if(s==null) {
  237.             s = initLockAttributeAuthority(nomePolicy);
  238.         }
  239.         return s;
  240.     }
  241.    
  242.     private static final Map<String, org.openspcoop2.utils.Semaphore> _lockGenericToken = new HashMap<>();
  243.     private static synchronized org.openspcoop2.utils.Semaphore initLockGenericToken(String funzione){
  244.         org.openspcoop2.utils.Semaphore s = _lockGenericToken.get(funzione);
  245.         if(s==null) {
  246.             Integer permits = OpenSPCoop2Properties.getInstance().getGestioneRetrieveTokenLockPermits();
  247.             if(permits!=null && permits.intValue()>1) {
  248.                 s = new org.openspcoop2.utils.Semaphore("GestoreGenericTokenCache_"+funzione, permits);
  249.             }
  250.             else {
  251.                 s = new org.openspcoop2.utils.Semaphore("GestoreGenericTokenCache_"+funzione);
  252.             }
  253.             _lockGenericToken.put(funzione, s);
  254.         }
  255.         return s;
  256.     }
  257.     private static org.openspcoop2.utils.Semaphore getLockGenericToken(String nomePolicy){
  258.         org.openspcoop2.utils.Semaphore s = _lockGenericToken.get(nomePolicy);
  259.         if(s==null) {
  260.             s = initLockGenericToken(nomePolicy);
  261.         }
  262.         return s;
  263.     }
  264.    
  265.  
  266.    

  267.     static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

  268.     /** Logger log */
  269.     private static Logger logger = null;
  270.     private static Logger logConsole = OpenSPCoop2Logger.getLoggerOpenSPCoopConsole();
  271.    
  272.     private static void loggerDebug(String msg) {
  273.         GestoreToken.logger.debug(msg);
  274.     }
  275.     private static void loggerInfo(String msg) {
  276.         GestoreToken.logger.info(msg);
  277.     }
  278.     private static void loggerError(String msg) {
  279.         GestoreToken.logger.error(msg);
  280.     }
  281.     private static void loggerError(String msg, Exception e) {
  282.         GestoreToken.logger.error(msg,e);
  283.     }
  284.     private static String getMessageObjectInCache(org.openspcoop2.utils.cache.CacheResponse response, String keyCache, String funzione) {
  285.         return "Oggetto (tipo:"+response.getObject().getClass().getName()+") con chiave ["+keyCache+"] (method:"+funzione+") in cache.";
  286.     }
  287.     private static String getMessageEccezioneInCache(org.openspcoop2.utils.cache.CacheResponse response, String keyCache, String funzione) {
  288.         return "Eccezione (tipo:"+response.getException().getClass().getName()+") con chiave ["+keyCache+"] (method:"+funzione+") in cache.";
  289.     }
  290.     private static final String MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE = "In cache non è presente ne un oggetto ne un'eccezione.";
  291.    
  292.     static final String TOKEN_NON_VALIDO = "Token non valido";
  293.     static String getMessageTokenNonValido(Exception e) {
  294.         return TOKEN_NON_VALIDO+": "+e.getMessage();
  295.     }
  296.    
  297.     static String getMessageViaProxy(String hostProxy, String portProxy) {
  298.         return " [via Proxy: "+hostProxy+":"+portProxy+"] ";
  299.     }
  300.    
  301.     static String getMessageErroreGovWayProxy(Exception e) {
  302.         return "Configurazione errata per la funzionalità govway-proxy; "+e.getMessage();
  303.     }
  304.    
  305.     static String getMessageConnettoreConnessioneSuccesso(ConnettoreBaseHTTP connettore) {
  306.         return "Connessione completata con successo (codice trasporto: "+connettore.getCodiceTrasporto()+")";
  307.     }
  308.     static String getMessageConnettoreConnessioneErrore(ConnettoreBaseHTTP connettore) {
  309.         return "Connessione terminata con errore (codice trasporto: "+connettore.getCodiceTrasporto()+")";
  310.     }
  311.     static final String CONNETTORE_RISPOSTA_NON_PERVENUTA = "; non è pervenuta alcuna risposta";
  312.    
  313.     public static final String KEY_ALIAS_UNDEFINED = "JWT Signature key alias undefined";
  314.     public static final String KEY_PASSWORD_UNDEFINED = "JWT Signature key password undefined";
  315.     public static final String KEYSTORE_TYPE_UNDEFINED = "JWT Signature keystore type undefined";
  316.     public static final String KEYSTORE_KEYPAIR_UNDEFINED = "JWT Signature keyPair undefined";
  317.     public static final String KEYSTORE_KEYSTORE_UNDEFINED = "JWT Signature keystore undefined";
  318.     public static final String KEYSTORE_KEYSTORE_FILE_UNDEFINED = "JWT Signature keystore file undefined";
  319.     public static final String KEYSTORE_KEYSTORE_PASSWORD_UNDEFINED = "JWT Signature keystore password undefined";
  320.     public static final String KEYSTORE_PRIVATE_KEY_UNDEFINED = "JWT Signature private key file undefined";
  321.     public static final String KEYSTORE_PUBLIC_KEY_UNDEFINED = "JWT Signature public key file undefined";
  322.     public static final String KEYSTORE_KEY_PAIR_ALGORITHM_UNDEFINED = "JWT Signature key pair algorithm undefined";
  323.    
  324.     /** Connettore Utils */
  325.     static void addProperties(ConnettoreMsg connettoreMsg, Properties p) {
  326.         if(p!=null && p.size()>0) {
  327.             Enumeration<?> en = p.propertyNames();
  328.             while (en.hasMoreElements()) {
  329.                 Object oKey = en.nextElement();
  330.                 if(oKey!=null) {
  331.                     String key = (String) oKey;
  332.                     String value = p.getProperty(key);
  333.                     connettoreMsg.getConnectorProperties().put(key,value);
  334.                 }
  335.             }
  336.         }
  337.     }
  338.    
  339.    
  340.     /* --------------- Cache --------------------*/
  341.     private static String getPrefixOggettoConChiave(String key) {
  342.          return "oggetto con chiave ["+key+"]";
  343.     }
  344.     private static String getSuffixEseguiOperazione(String funzione) {
  345.         return " (method:"+funzione+") eseguo operazione...";
  346.     }
  347.     private static String getMessaggioAggiuntaOggettoInCache(String keyCache) {
  348.         return "Aggiungo oggetto ["+keyCache+"] in cache";
  349.     }
  350.     private static String getMessaggioErroreInserimentoInCache(String keyCache, Exception e) {
  351.         return "Errore durante l'inserimento in cache ["+keyCache+"]: "+e.getMessage();
  352.     }
  353.     private static String getMessaggioErroreValoreEsitoNull(String funzione) {
  354.         return "Metodo (GestoreToken."+funzione+") ha ritornato un valore di esito null";
  355.     }
  356.    
  357.     public static void resetGestioneTokenCache() throws TokenException{
  358.         if(GestoreToken.cacheGestioneToken!=null){
  359.             try{
  360.                 GestoreToken.cacheGestioneToken.clear();
  361.             }catch(Exception e){
  362.                 throw new TokenException(e.getMessage(),e);
  363.             }
  364.         }
  365.     }
  366.     public static void resetAttributeAuthorityCache() throws TokenException{
  367.         if(GestoreToken.cacheAttributeAuthority!=null){
  368.             try{
  369.                 GestoreToken.cacheAttributeAuthority.clear();
  370.             }catch(Exception e){
  371.                 throw new TokenException(e.getMessage(),e);
  372.             }
  373.         }
  374.     }
  375.    
  376.     public static String printStatsGestioneTokenCache(String separator) throws TokenException{
  377.         try{
  378.             if(GestoreToken.cacheGestioneToken!=null){
  379.                 return GestoreToken.cacheGestioneToken.printStats(separator);
  380.             }
  381.             else{
  382.                 throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  383.             }
  384.         }catch(Exception e){
  385.             throw new TokenException("Visualizzazione Statistiche riguardante la cache sulla gestione dei token non riuscita: "+e.getMessage(),e);
  386.         }
  387.     }
  388.     public static String printStatsAttributeAuthorityCache(String separator) throws TokenException{
  389.         try{
  390.             if(GestoreToken.cacheAttributeAuthority!=null){
  391.                 return GestoreToken.cacheAttributeAuthority.printStats(separator);
  392.             }
  393.             else{
  394.                 throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  395.             }
  396.         }catch(Exception e){
  397.             throw new TokenException("Visualizzazione Statistiche riguardante la cache sui dati delle Attribute Authority non riuscita: "+e.getMessage(),e);
  398.         }
  399.     }
  400.    
  401.     public static void abilitaGestioneTokenCache() throws TokenException{
  402.         if(GestoreToken.cacheGestioneToken!=null)
  403.             throw new TokenException(Constants.MSG_CACHE_GIA_ABILITATA);
  404.         else{
  405.             abilitaGestioneTokenCacheEngine();
  406.         }
  407.     }
  408.     public static void abilitaAttributeAuthorityCache() throws TokenException{
  409.         if(GestoreToken.cacheAttributeAuthority!=null)
  410.             throw new TokenException(Constants.MSG_CACHE_GIA_ABILITATA);
  411.         else{
  412.             abilitaAttributeAuthorityCacheEngine();
  413.         }
  414.     }
  415.    
  416.     private static synchronized void abilitaGestioneTokenCacheEngine() throws TokenException{
  417.         if(GestoreToken.cacheGestioneToken==null) {
  418.             try{
  419.                 GestoreToken.cacheGestioneToken = new Cache(CacheType.JCS, GestoreToken.GESTIONE_TOKEN_CACHE_NAME); // lascio JCS come default abilitato via jmx
  420.                 GestoreToken.cacheGestioneToken.build();
  421.             }catch(Exception e){
  422.                 throw new TokenException(e.getMessage(),e);
  423.             }
  424.         }
  425.     }
  426.     private static synchronized void abilitaAttributeAuthorityCacheEngine() throws TokenException{
  427.         if(GestoreToken.cacheAttributeAuthority==null) {
  428.             try{
  429.                 GestoreToken.cacheAttributeAuthority = new Cache(CacheType.JCS, GestoreToken.ATTRIBUTE_AUTHORITY_CACHE_NAME); // lascio JCS come default abilitato via jmx
  430.                 GestoreToken.cacheAttributeAuthority.build();
  431.             }catch(Exception e){
  432.                 throw new TokenException(e.getMessage(),e);
  433.             }
  434.         }
  435.     }
  436.    
  437.     public static void abilitaGestioneTokenCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond) throws TokenException{
  438.         if(GestoreToken.cacheGestioneToken!=null)
  439.             throw new TokenException(Constants.MSG_CACHE_GIA_ABILITATA);
  440.         else{
  441.             try{
  442.                 setGestioneTokenCache(dimensioneCache, algoritmoCacheLRU, itemIdleTime, itemLifeSecond);
  443.             }catch(Exception e){
  444.                 throw new TokenException(e.getMessage(),e);
  445.             }
  446.         }
  447.     }
  448.     public static void abilitaAttributeAuthorityCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond) throws TokenException{
  449.         if(GestoreToken.cacheAttributeAuthority!=null)
  450.             throw new TokenException(Constants.MSG_CACHE_GIA_ABILITATA);
  451.         else{
  452.             try{
  453.                 setAttributeAuthorityCache(dimensioneCache, algoritmoCacheLRU, itemIdleTime, itemLifeSecond);
  454.             }catch(Exception e){
  455.                 throw new TokenException(e.getMessage(),e);
  456.             }
  457.         }
  458.     }
  459.    
  460.     private static void setGestioneTokenCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond) throws TokenException, UtilsException{
  461.         int dimensioneCacheInt = -1;
  462.         if(dimensioneCache!=null){
  463.             dimensioneCacheInt = dimensioneCache.intValue();
  464.         }
  465.        
  466.         String algoritmoCache = null;
  467.         if(algoritmoCacheLRU!=null){
  468.             if(algoritmoCacheLRU)
  469.                  algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  470.             else
  471.                  algoritmoCache = CostantiConfigurazione.CACHE_MRU.toString();
  472.         }else{
  473.             algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  474.         }
  475.        
  476.         long itemIdleTimeLong = -1;
  477.         if(itemIdleTime!=null){
  478.             itemIdleTimeLong = itemIdleTime;
  479.         }
  480.        
  481.         long itemLifeSecondLong = -1;
  482.         if(itemLifeSecond!=null){
  483.             itemLifeSecondLong = itemLifeSecond;
  484.         }
  485.        
  486.         GestoreToken.initGestioneTokenCacheToken(CacheType.JCS, dimensioneCacheInt, algoritmoCache, itemIdleTimeLong, itemLifeSecondLong, null); // lascio JCS come default abilitato via jmx
  487.     }
  488.     private static void setAttributeAuthorityCache(Long dimensioneCache,Boolean algoritmoCacheLRU,Long itemIdleTime,Long itemLifeSecond) throws TokenException, UtilsException{
  489.         int dimensioneCacheInt = -1;
  490.         if(dimensioneCache!=null){
  491.             dimensioneCacheInt = dimensioneCache.intValue();
  492.         }
  493.        
  494.         String algoritmoCache = null;
  495.         if(algoritmoCacheLRU!=null){
  496.             if(algoritmoCacheLRU)
  497.                  algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  498.             else
  499.                  algoritmoCache = CostantiConfigurazione.CACHE_MRU.toString();
  500.         }else{
  501.             algoritmoCache = CostantiConfigurazione.CACHE_LRU.toString();
  502.         }
  503.        
  504.         long itemIdleTimeLong = -1;
  505.         if(itemIdleTime!=null){
  506.             itemIdleTimeLong = itemIdleTime;
  507.         }
  508.        
  509.         long itemLifeSecondLong = -1;
  510.         if(itemLifeSecond!=null){
  511.             itemLifeSecondLong = itemLifeSecond;
  512.         }
  513.        
  514.         GestoreToken.initAttributeAuthorityCacheToken(CacheType.JCS, dimensioneCacheInt, algoritmoCache, itemIdleTimeLong, itemLifeSecondLong, null); // lascio JCS come default abilitato via jmx
  515.     }
  516.    
  517.     public static void disabilitaGestioneTokenCache() throws TokenException{
  518.         if(GestoreToken.cacheGestioneToken==null)
  519.             throw new TokenException(Constants.MSG_CACHE_GIA_DISABILITATA);
  520.         else{
  521.             disabilitaGestioneTokenCacheEngine();
  522.         }
  523.     }
  524.     public static void disabilitaAttributeAuthorityCache() throws TokenException{
  525.         if(GestoreToken.cacheAttributeAuthority==null)
  526.             throw new TokenException(Constants.MSG_CACHE_GIA_DISABILITATA);
  527.         else{
  528.             disabilitaAttributeAuthorityCacheEngine();
  529.         }
  530.     }
  531.    
  532.     private static synchronized void disabilitaGestioneTokenCacheEngine() throws TokenException{
  533.         if(GestoreToken.cacheGestioneToken!=null) {
  534.             try{
  535.                 GestoreToken.cacheGestioneToken.clear();
  536.                 GestoreToken.cacheGestioneToken = null;
  537.             }catch(Exception e){
  538.                 throw new TokenException(e.getMessage(),e);
  539.             }
  540.         }
  541.     }
  542.     private static synchronized void disabilitaAttributeAuthorityCacheEngine() throws TokenException{
  543.         if(GestoreToken.cacheAttributeAuthority!=null) {
  544.             try{
  545.                 GestoreToken.cacheAttributeAuthority.clear();
  546.                 GestoreToken.cacheAttributeAuthority = null;
  547.             }catch(Exception e){
  548.                 throw new TokenException(e.getMessage(),e);
  549.             }
  550.         }
  551.     }
  552.    
  553.     public static boolean isGestioneTokenCacheAbilitata(){
  554.         return GestoreToken.cacheGestioneToken != null;
  555.     }
  556.     public static boolean isAttributeAuthorityCacheAbilitata(){
  557.         return GestoreToken.cacheAttributeAuthority != null;
  558.     }
  559.    
  560.     public static String listKeysGestioneTokenCache(String separator) throws TokenException{
  561.         if(GestoreToken.cacheGestioneToken!=null){
  562.             try{
  563.                 return GestoreToken.cacheGestioneToken.printKeys(separator);
  564.             }catch(Exception e){
  565.                 throw new TokenException(e.getMessage(),e);
  566.             }
  567.         }else{
  568.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  569.         }
  570.     }
  571.     public static String listKeysAttributeAuthorityCache(String separator) throws TokenException{
  572.         if(GestoreToken.cacheAttributeAuthority!=null){
  573.             try{
  574.                 return GestoreToken.cacheAttributeAuthority.printKeys(separator);
  575.             }catch(Exception e){
  576.                 throw new TokenException(e.getMessage(),e);
  577.             }
  578.         }else{
  579.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  580.         }
  581.     }
  582.    
  583.     public static List<String> keysGestioneTokenCache() throws TokenException{
  584.         if(GestoreToken.cacheGestioneToken!=null){
  585.             try{
  586.                 return GestoreToken.cacheGestioneToken.keys();
  587.             }catch(Exception e){
  588.                 throw new TokenException(e.getMessage(),e);
  589.             }
  590.         }else{
  591.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  592.         }
  593.     }
  594.     public static List<String> keysAttributeAuthorityCache() throws TokenException{
  595.         if(GestoreToken.cacheAttributeAuthority!=null){
  596.             try{
  597.                 return GestoreToken.cacheAttributeAuthority.keys();
  598.             }catch(Exception e){
  599.                 throw new TokenException(e.getMessage(),e);
  600.             }
  601.         }else{
  602.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  603.         }
  604.     }
  605.    
  606.     public static String getObjectGestioneTokenCache(String key) throws TokenException{
  607.         if(GestoreToken.cacheGestioneToken!=null){
  608.             try{
  609.                 Object o = GestoreToken.cacheGestioneToken.get(key);
  610.                 if(o!=null){
  611.                     return o.toString();
  612.                 }else{
  613.                     return getPrefixOggettoConChiave(key)+" non presente";
  614.                 }
  615.             }catch(Exception e){
  616.                 throw new TokenException(e.getMessage(),e);
  617.             }
  618.         }else{
  619.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  620.         }
  621.     }
  622.     public static String getObjectAttributeAuthorityCache(String key) throws TokenException{
  623.         if(GestoreToken.cacheAttributeAuthority!=null){
  624.             try{
  625.                 Object o = GestoreToken.cacheAttributeAuthority.get(key);
  626.                 if(o!=null){
  627.                     return o.toString();
  628.                 }else{
  629.                     return getPrefixOggettoConChiave(key)+" non presente";
  630.                 }
  631.             }catch(Exception e){
  632.                 throw new TokenException(e.getMessage(),e);
  633.             }
  634.         }else{
  635.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  636.         }
  637.     }
  638.    
  639.     public static void removeObjectGestioneTokenCache(String key) throws TokenException{
  640.         if(GestoreToken.cacheGestioneToken!=null){
  641.             try{
  642.                 GestoreToken.cacheGestioneToken.remove(key);
  643.             }catch(Exception e){
  644.                 throw new TokenException(e.getMessage(),e);
  645.             }
  646.         }else{
  647.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  648.         }
  649.     }
  650.     public static void removeObjectAttributeAuthorityCache(String key) throws TokenException{
  651.         if(GestoreToken.cacheAttributeAuthority!=null){
  652.             try{
  653.                 GestoreToken.cacheAttributeAuthority.remove(key);
  654.             }catch(Exception e){
  655.                 throw new TokenException(e.getMessage(),e);
  656.             }
  657.         }else{
  658.             throw new TokenException(Constants.MSG_CACHE_NON_ABILITATA);
  659.         }
  660.     }
  661.    
  662.    
  663.    
  664.    
  665.    
  666.     /*----------------- CLEANER --------------------*/
  667.    
  668.     public static void removeGenericPropertiesGestioneToken(IDGenericProperties idGP) throws TokenException {
  669.        
  670.         if(GestoreToken.isGestioneTokenCacheAbilitata()){
  671.            
  672.             String prefixKeyValidazioneJwt = null;
  673.             String prefixKeyIntrospection = null;
  674.             String prefixKeyUserInfo = null;
  675.            
  676.             String prefixKeyRetrieveToken = null;
  677.            
  678.             boolean checkKeys = false;
  679.            
  680.             if(CostantiConfigurazione.GENERIC_PROPERTIES_TOKEN_TIPOLOGIA_VALIDATION.equals(idGP.getTipologia())) {
  681.                
  682.                 prefixKeyValidazioneJwt = GestoreTokenValidazioneUtilities.buildPrefixCacheKeyValidazione(idGP.getNome(), VALIDAZIONE_JWT_FUNCTION);
  683.                 prefixKeyIntrospection = GestoreTokenValidazioneUtilities.buildPrefixCacheKeyValidazione(idGP.getNome(), INTROSPECTION_FUNCTION);
  684.                 prefixKeyUserInfo = GestoreTokenValidazioneUtilities.buildPrefixCacheKeyValidazione(idGP.getNome(), USERINFO_FUNCTION);
  685.                
  686.                 checkKeys = true;
  687.             }
  688.             else if(CostantiConfigurazione.GENERIC_PROPERTIES_TOKEN_TIPOLOGIA_RETRIEVE.equals(idGP.getTipologia())) {
  689.                
  690.                 prefixKeyRetrieveToken = GestoreTokenNegoziazioneUtilities.buildPrefixCacheKeyNegoziazione(idGP.getNome(), RETRIEVE_FUNCTION);
  691.                
  692.                 checkKeys = true;
  693.                
  694.             }
  695.            
  696.             if(checkKeys) {
  697.                 checkKeys(prefixKeyValidazioneJwt, prefixKeyIntrospection, prefixKeyUserInfo,
  698.                         prefixKeyRetrieveToken);
  699.             }
  700.                
  701.         }
  702.        
  703.     }
  704.     public static void removeGenericPropertiesAttributeAuthority(IDGenericProperties idGP) throws TokenException {
  705.        
  706.         if(GestoreToken.isAttributeAuthorityCacheAbilitata()){
  707.                        
  708.             String prefixKeyAA = null;
  709.            
  710.             boolean checkKeys = false;
  711.            
  712.             if(CostantiConfigurazione.GENERIC_PROPERTIES_ATTRIBUTE_AUTHORITY.equals(idGP.getTipologia())) {
  713.                
  714.                 prefixKeyAA = GestoreTokenAttributeAuthorityUtilities.buildCacheKeyRecuperoAttributiPrefix(idGP.getNome(), ATTRIBUTE_AUTHORITY_FUNCTION);
  715.                
  716.                 checkKeys = true;
  717.             }
  718.            
  719.             if(checkKeys) {
  720.                 checkKeys(prefixKeyAA);
  721.             }
  722.                
  723.         }
  724.        
  725.     }
  726.     private static void checkKeys(String prefixKeyValidazioneJwt, String prefixKeyIntrospection, String prefixKeyUserInfo,
  727.             String prefixKeyRetrieveToken) throws TokenException {
  728.         List<String> keyForClean = new ArrayList<>();
  729.         List<String> keys = GestoreToken.keysGestioneTokenCache();
  730.         if(keys!=null && !keys.isEmpty()) {
  731.             fillKeyForClean(prefixKeyValidazioneJwt, prefixKeyIntrospection, prefixKeyUserInfo,
  732.                     prefixKeyRetrieveToken, null,
  733.                     keys, keyForClean);
  734.         }
  735.         if(!keyForClean.isEmpty()) {
  736.             for (String key : keyForClean) {
  737.                 removeObjectGestioneTokenCache(key);
  738.             }
  739.         }
  740.     }
  741.     private static void checkKeys(String prefixKeyAA) throws TokenException {
  742.         List<String> keyForClean = new ArrayList<>();
  743.         List<String> keys = GestoreToken.keysAttributeAuthorityCache();
  744.         if(keys!=null && !keys.isEmpty()) {
  745.             fillKeyForClean(null, null, null,
  746.                     null, prefixKeyAA,
  747.                     keys, keyForClean);
  748.         }
  749.         if(!keyForClean.isEmpty()) {
  750.             for (String key : keyForClean) {
  751.                 removeObjectAttributeAuthorityCache(key);
  752.             }
  753.         }
  754.     }
  755.     private static void fillKeyForClean(String prefixKeyValidazioneJwt, String prefixKeyIntrospection, String prefixKeyUserInfo,
  756.             String prefixKeyRetrieveToken, String prefixKeyAA,
  757.             List<String> keys, List<String> keyForClean) {
  758.         for (String key : keys) {
  759.             if(key!=null &&
  760.                 (
  761.                         (prefixKeyValidazioneJwt!=null && key.startsWith(prefixKeyValidazioneJwt))
  762.                         ||
  763.                         (prefixKeyIntrospection!=null && key.startsWith(prefixKeyIntrospection))
  764.                         ||
  765.                         (prefixKeyUserInfo!=null && key.startsWith(prefixKeyUserInfo))
  766.                         ||
  767.                         (prefixKeyRetrieveToken!=null && key.startsWith(prefixKeyRetrieveToken))
  768.                         ||
  769.                         (prefixKeyAA!=null && key.startsWith(prefixKeyAA))
  770.                     )
  771.                 ){
  772.                 keyForClean.add(key);
  773.             }
  774.         }
  775.     }
  776.    
  777.    
  778.    
  779.    


  780.     /*----------------- INIZIALIZZAZIONE --------------------*/
  781.     public static void initializeGestioneToken(Logger log) throws TokenException, UtilsException{
  782.         GestoreToken.initializeGestioneToken(null, false, -1,null,-1l,-1l, log);
  783.     }
  784.     public static void initializeGestioneToken(CacheType cacheType,
  785.             int dimensioneCache,String algoritmoCache,
  786.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException{
  787.         GestoreToken.initializeGestioneToken(cacheType, true, dimensioneCache,algoritmoCache,idleTime,itemLifeSecond, log);
  788.     }
  789.     private static void initializeGestioneToken(CacheType cacheType,
  790.             boolean cacheAbilitata,int dimensioneCache,String algoritmoCache,
  791.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException{

  792.         // Inizializzo log
  793.         GestoreToken.logger = log;
  794.                
  795.         // Inizializzazione Cache
  796.         if(cacheAbilitata){
  797.             GestoreToken.initGestioneTokenCacheToken(cacheType, dimensioneCache, algoritmoCache, idleTime, itemLifeSecond, log);
  798.         }

  799.     }
  800.    
  801.     public static void initializeAttributeAuthority(Logger log) throws TokenException, UtilsException{
  802.         GestoreToken.initializeAttributeAuthority(null, false, -1,null,-1l,-1l, log);
  803.     }
  804.     public static void initializeAttributeAuthority(CacheType cacheType,
  805.             int dimensioneCache,String algoritmoCache,
  806.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException{
  807.         GestoreToken.initializeAttributeAuthority(cacheType, true, dimensioneCache,algoritmoCache,idleTime,itemLifeSecond, log);
  808.     }
  809.     private static void initializeAttributeAuthority(CacheType cacheType,
  810.             boolean cacheAbilitata,int dimensioneCache,String algoritmoCache,
  811.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException{

  812.         // Inizializzo log
  813.         GestoreToken.logger = log;
  814.                
  815.         // Inizializzazione Cache
  816.         if(cacheAbilitata){
  817.             GestoreToken.initAttributeAuthorityCacheToken(cacheType, dimensioneCache, algoritmoCache, idleTime, itemLifeSecond, log);
  818.         }

  819.     }


  820.     public static void initGestioneTokenCacheToken(CacheType cacheType, int dimensioneCache,String algoritmoCache,
  821.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException {
  822.        
  823.         if(log!=null)
  824.             log.info("Inizializzazione cache GestioneToken");

  825.         GestoreToken.cacheGestioneToken = new Cache(cacheType, GestoreToken.GESTIONE_TOKEN_CACHE_NAME);

  826.         if( (dimensioneCache>0) ||
  827.                 (algoritmoCache != null) ){

  828.             initGestioneTokenCacheSize(dimensioneCache, algoritmoCache, log);

  829.         }

  830.         if( idleTime > 0  ){
  831.             try{
  832.                 String msg = "Attributo 'IdleTime' (Token) impostato al valore: "+idleTime;
  833.                 if(log!=null)
  834.                     log.info(msg);
  835.                 GestoreToken.logConsole.info(msg);
  836.                 GestoreToken.cacheGestioneToken.setItemIdleTime(idleTime);
  837.             }catch(Exception error){
  838.                 throw new TokenException("Parametro errato per l'attributo 'IdleTime' (Token): "+error.getMessage(),error);
  839.             }
  840.         }
  841.         try{
  842.             String msg = "Attributo 'MaxLifeSecond' (Token) impostato al valore: "+itemLifeSecond;
  843.             if(log!=null)
  844.                 log.info(msg);
  845.             GestoreToken.logConsole.info(msg);
  846.             GestoreToken.cacheGestioneToken.setItemLifeTime(itemLifeSecond);
  847.         }catch(Exception error){
  848.             throw new TokenException("Parametro errato per l'attributo 'MaxLifeSecond' (Token): "+error.getMessage(),error);
  849.         }

  850.         GestoreToken.cacheGestioneToken.build();
  851.     }
  852.     public static void initAttributeAuthorityCacheToken(CacheType cacheType, int dimensioneCache,String algoritmoCache,
  853.             long idleTime, long itemLifeSecond, Logger log) throws TokenException, UtilsException {
  854.        
  855.         if(log!=null)
  856.             log.info("Inizializzazione cache Token");

  857.         GestoreToken.cacheAttributeAuthority = new Cache(cacheType, GestoreToken.ATTRIBUTE_AUTHORITY_CACHE_NAME);

  858.         if( (dimensioneCache>0) ||
  859.                 (algoritmoCache != null) ){

  860.             initCacheSize(dimensioneCache, algoritmoCache, log);

  861.         }

  862.         if( idleTime > 0  ){
  863.             try{
  864.                 String msg = "Attributo 'IdleTime' (AttributeAuthority) impostato al valore: "+idleTime;
  865.                 if(log!=null)
  866.                     log.info(msg);
  867.                 GestoreToken.logConsole.info(msg);
  868.                 GestoreToken.cacheAttributeAuthority.setItemIdleTime(idleTime);
  869.             }catch(Exception error){
  870.                 throw new TokenException("Parametro errato per l'attributo 'IdleTime' (AttributeAuthority): "+error.getMessage(),error);
  871.             }
  872.         }
  873.         try{
  874.             String msg = "Attributo 'MaxLifeSecond' (AttributeAuthority) impostato al valore: "+itemLifeSecond;
  875.             if(log!=null)
  876.                 log.info(msg);
  877.             GestoreToken.logConsole.info(msg);
  878.             GestoreToken.cacheAttributeAuthority.setItemLifeTime(itemLifeSecond);
  879.         }catch(Exception error){
  880.             throw new TokenException("Parametro errato per l'attributo 'MaxLifeSecond' (AttributeAuthority): "+error.getMessage(),error);
  881.         }

  882.         GestoreToken.cacheAttributeAuthority.build();
  883.     }
  884.    
  885.     public static void initGestioneTokenCacheSize(int dimensioneCache,String algoritmoCache, Logger log) throws TokenException {
  886.         if( dimensioneCache>0 ){
  887.             try{
  888.                 String msg = "Dimensione della cache (Token) impostata al valore: "+dimensioneCache;
  889.                 if(log!=null)
  890.                     log.info(msg);
  891.                 GestoreToken.logConsole.info(msg);
  892.                 GestoreToken.cacheGestioneToken.setCacheSize(dimensioneCache);
  893.             }catch(Exception error){
  894.                 throw new TokenException("Parametro errato per la dimensione della cache (Token): "+error.getMessage(),error);
  895.             }
  896.         }
  897.         if(algoritmoCache != null ){
  898.             String msg = "Algoritmo di cache (Token) impostato al valore: "+algoritmoCache;
  899.             if(log!=null)
  900.                 log.info(msg);
  901.             GestoreToken.logConsole.info(msg);
  902.             if(CostantiConfigurazione.CACHE_MRU.toString().equalsIgnoreCase(algoritmoCache))
  903.                 GestoreToken.cacheGestioneToken.setCacheAlgoritm(CacheAlgorithm.MRU);
  904.             else
  905.                 GestoreToken.cacheGestioneToken.setCacheAlgoritm(CacheAlgorithm.LRU);
  906.         }
  907.     }
  908.     public static void initCacheSize(int dimensioneCache,String algoritmoCache, Logger log) throws TokenException {
  909.         if( dimensioneCache>0 ){
  910.             try{
  911.                 String msg = "Dimensione della cache (AttributeAuthority) impostata al valore: "+dimensioneCache;
  912.                 if(log!=null)
  913.                     log.info(msg);
  914.                 GestoreToken.logConsole.info(msg);
  915.                 GestoreToken.cacheAttributeAuthority.setCacheSize(dimensioneCache);
  916.             }catch(Exception error){
  917.                 throw new TokenException("Parametro errato per la dimensione della cache (AttributeAuthority): "+error.getMessage(),error);
  918.             }
  919.         }
  920.         if(algoritmoCache != null ){
  921.             String msg = "Algoritmo di cache (AttributeAuthority) impostato al valore: "+algoritmoCache;
  922.             if(log!=null)
  923.                 log.info(msg);
  924.             GestoreToken.logConsole.info(msg);
  925.             if(CostantiConfigurazione.CACHE_MRU.toString().equalsIgnoreCase(algoritmoCache))
  926.                 GestoreToken.cacheAttributeAuthority.setCacheAlgoritm(CacheAlgorithm.MRU);
  927.             else
  928.                 GestoreToken.cacheAttributeAuthority.setCacheAlgoritm(CacheAlgorithm.LRU);
  929.         }
  930.     }
  931.    
  932.    

  933.    
  934.    
  935.    
  936.    
  937.     // ********* [VALIDAZIONE-TOKEN] VALIDAZIONE CONFIGURAZIONE ****************** */
  938.    
  939.     public static void validazioneConfigurazione(AbstractDatiInvocazione datiInvocazione) throws ProviderException, ProviderValidationException {
  940.         TokenProvider p = new TokenProvider();
  941.         p.validate(datiInvocazione.getPolicyGestioneToken().getProperties());
  942.     }
  943.    
  944.    
  945.    
  946.    
  947.     // ********* [VALIDAZIONE-TOKEN] VERIFICA POSIZIONE TOKEN ****************** */
  948.    
  949.     private static final String INFO_TRASPORTO_NON_PRESENTI = "Informazioni di trasporto non presenti";
  950.     private static final String CONTENENTE_IL_TOKEN = "contenente il token";
  951.    
  952.     public static EsitoPresenzaToken verificaPosizioneToken(AbstractDatiInvocazione datiInvocazione, boolean portaDelegata) {
  953.        
  954.         EsitoPresenzaToken esitoPresenzaToken = null;
  955.         if(portaDelegata) {
  956.             esitoPresenzaToken = new EsitoPresenzaTokenPortaDelegata();
  957.         }
  958.         else {
  959.             esitoPresenzaToken = new EsitoPresenzaTokenPortaApplicativa();
  960.         }
  961.        
  962.         esitoPresenzaToken.setPresente(false);
  963.         try{
  964.             PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  965.             String source = policyGestioneToken.getTokenSource();
  966.            

  967.             String token = null;

  968.             String detailsErrorHeader = null;
  969.             if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source) ||
  970.                     Costanti.POLICY_TOKEN_SOURCE_RFC6750_HEADER.equals(source) ||
  971.                     Costanti.POLICY_TOKEN_SOURCE_CUSTOM_HEADER.equals(source)) {
  972.                 if(datiInvocazione.getInfoConnettoreIngresso()==null ||
  973.                         datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext()==null) {
  974.                     detailsErrorHeader = INFO_TRASPORTO_NON_PRESENTI;
  975.                 }
  976.                 else {
  977.                     URLProtocolContext urlProtocolContext = datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext();
  978.                     if(urlProtocolContext.getHeaders()==null || urlProtocolContext.getHeaders().size()<=0) {
  979.                         detailsErrorHeader = "Header di trasporto non presenti";
  980.                     }
  981.                     if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source) ||
  982.                             Costanti.POLICY_TOKEN_SOURCE_RFC6750_HEADER.equals(source)) {
  983.                         if(urlProtocolContext.getCredential()==null || urlProtocolContext.getCredential().getBearerToken()==null) {
  984.                             if(urlProtocolContext.getCredential()!=null && urlProtocolContext.getCredential().getUsername()!=null) {
  985.                                 detailsErrorHeader = "Riscontrato header http '"+HttpConstants.AUTHORIZATION+"' valorizzato tramite autenticazione '"+HttpConstants.AUTHORIZATION_PREFIX_BASIC+
  986.                                         "'; la configurazione richiede invece la presenza di un token valorizzato tramite autenticazione '"+HttpConstants.AUTHORIZATION_PREFIX_BEARER+"' ";
  987.                             }
  988.                             else {
  989.                                 detailsErrorHeader = "Non è stato riscontrato un header http '"+HttpConstants.AUTHORIZATION+"' valorizzato tramite autenticazione '"+HttpConstants.AUTHORIZATION_PREFIX_BEARER+"' e contenente un token";
  990.                             }
  991.                         }
  992.                         else {
  993.                             token = urlProtocolContext.getCredential().getBearerToken();
  994.                             esitoPresenzaToken.setHeaderHttp(HttpConstants.AUTHORIZATION);
  995.                         }
  996.                     }
  997.                     else {
  998.                         String headerName = policyGestioneToken.getTokenSourceHeaderName();
  999.                         List<String> values =  urlProtocolContext.getHeaderValues(headerName);
  1000.                         if(values!=null && !values.isEmpty()) {
  1001.                             token = values.get(0);
  1002.                         }
  1003.                         if(token==null) {
  1004.                             detailsErrorHeader = "Non è stato riscontrato l'header http '"+headerName+"' "+CONTENENTE_IL_TOKEN;
  1005.                         }
  1006.                         else if(values.size()>1) {
  1007.                             detailsErrorHeader = "Sono stati rilevati più di un header http '"+headerName+"'";
  1008.                         }
  1009.                         else {
  1010.                             esitoPresenzaToken.setHeaderHttp(headerName);
  1011.                         }
  1012.                     }
  1013.                 }
  1014.             }
  1015.            
  1016.             String detailsErrorUrl = null;
  1017.             if( (token==null && Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source)) ||
  1018.                     Costanti.POLICY_TOKEN_SOURCE_RFC6750_URL.equals(source) ||
  1019.                     Costanti.POLICY_TOKEN_SOURCE_CUSTOM_URL.equals(source)) {
  1020.                 if(datiInvocazione.getInfoConnettoreIngresso()==null ||
  1021.                         datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext()==null) {
  1022.                     detailsErrorUrl = INFO_TRASPORTO_NON_PRESENTI;
  1023.                 }
  1024.                 else {
  1025.                     URLProtocolContext urlProtocolContext = datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext();
  1026.                     if(urlProtocolContext.getParameters()==null || urlProtocolContext.getParameters().size()<=0) {
  1027.                         detailsErrorUrl = "Parametri nella URL non presenti";
  1028.                     }
  1029.                     String propertyUrlName = null;
  1030.                     if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source) ||
  1031.                             Costanti.POLICY_TOKEN_SOURCE_RFC6750_URL.equals(source)) {
  1032.                         propertyUrlName = Costanti.RFC6750_URI_QUERY_PARAMETER_ACCESS_TOKEN;
  1033.                     }
  1034.                     else {
  1035.                         propertyUrlName = policyGestioneToken.getTokenSourceUrlPropertyName();
  1036.                     }
  1037.                     List<String> values = urlProtocolContext.getParameterValues(propertyUrlName);
  1038.                     if(values!=null && !values.isEmpty()) {
  1039.                         token = values.get(0);
  1040.                     }
  1041.                     if(token==null) {
  1042.                         detailsErrorUrl = "Non è stato riscontrata la proprietà della URL '"+propertyUrlName+"' "+CONTENENTE_IL_TOKEN;
  1043.                     }
  1044.                     else if(values.size()>1) {
  1045.                         detailsErrorHeader = "Sono state rilevate più proprietà della URL '"+propertyUrlName+"'";
  1046.                     }
  1047.                     else {
  1048.                         esitoPresenzaToken.setPropertyUrl(propertyUrlName);
  1049.                     }
  1050.                 }
  1051.             }
  1052.            
  1053.             String detailsErrorForm = null;
  1054.             if( (token==null && Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source)) ||
  1055.                     Costanti.POLICY_TOKEN_SOURCE_RFC6750_FORM.equals(source)) {
  1056.                 if(datiInvocazione.getInfoConnettoreIngresso()==null ||
  1057.                         datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext()==null ||
  1058.                         datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext().getHttpServletRequest()==null) {
  1059.                     detailsErrorForm = INFO_TRASPORTO_NON_PRESENTI;
  1060.                 }
  1061.                 else {
  1062.                     HttpServletRequest httpServletRequest = datiInvocazione.getInfoConnettoreIngresso().getUrlProtocolContext().getHttpServletRequest();
  1063.                     if(httpServletRequest instanceof FormUrlEncodedHttpServletRequest) {
  1064.                         FormUrlEncodedHttpServletRequest form = (FormUrlEncodedHttpServletRequest) httpServletRequest;
  1065.                         List<String> values = form.getFormUrlEncodedParameterValues(Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN);
  1066.                         if(values!=null && !values.isEmpty()) {
  1067.                             token = values.get(0);
  1068.                         }
  1069.                         if(token==null) {
  1070.                             detailsErrorForm = "Non è stato riscontrata la proprietà della Form '"+Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN+"' "+CONTENENTE_IL_TOKEN;
  1071.                         }
  1072.                         else if(values.size()>1) {
  1073.                             detailsErrorHeader = "Sono state rilevate più proprietà della Form '"+Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN+"'";
  1074.                         }
  1075.                         else {
  1076.                             esitoPresenzaToken.setPropertyFormBased(Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN);
  1077.                         }
  1078.                     }
  1079.                     else if(FormUrlEncodedHttpServletRequest.isFormUrlEncodedRequest(httpServletRequest)) {
  1080.                         List<String> values = TransportUtils.getParameterValues(httpServletRequest, Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN);
  1081.                         if(values!=null && !values.isEmpty()) {
  1082.                             token = values.get(0);
  1083.                         }
  1084.                         if(token==null) {
  1085.                             detailsErrorForm = "Non è stato riscontrata la proprietà della Form '"+Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN+"' "+CONTENENTE_IL_TOKEN;
  1086.                         }
  1087.                         else if(values.size()>1) {
  1088.                             detailsErrorHeader = "Sono state rilevate più proprietà della Form '"+Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN+"'";
  1089.                         }
  1090.                         else {
  1091.                             esitoPresenzaToken.setPropertyFormBased(Costanti.RFC6750_FORM_PARAMETER_ACCESS_TOKEN);
  1092.                         }
  1093.                     }
  1094.                     else {
  1095.                         detailsErrorForm = "Non è stato riscontrata la presenza di un contenuto 'Form-Encoded'";
  1096.                     }
  1097.                 }
  1098.             }
  1099.            
  1100.             String detailsError = null;
  1101.             if(detailsErrorHeader!=null) {
  1102.                 if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source)) {
  1103.                     if(detailsErrorUrl!=null || detailsErrorForm!=null) {
  1104.                         detailsError = "\n";
  1105.                     }
  1106.                     else {
  1107.                         detailsError = "";
  1108.                     }
  1109.                     detailsError = detailsError + "(Authorization Request Header) " +detailsErrorHeader;
  1110.                 }
  1111.                 else {
  1112.                     detailsError = detailsErrorHeader;
  1113.                 }
  1114.             }
  1115.             if(detailsErrorUrl!=null) {
  1116.                 if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source)) {
  1117.                     if(detailsError!=null) {
  1118.                         detailsError = detailsError+"\n";
  1119.                     }
  1120.                     else {
  1121.                         if(detailsErrorForm!=null) {
  1122.                             detailsError = "\n";
  1123.                         }
  1124.                         else {
  1125.                             detailsError = "";
  1126.                         }
  1127.                     }
  1128.                     detailsError = detailsError + "(URI Query Parameter) " +detailsErrorUrl;
  1129.                 }
  1130.                 else {
  1131.                     detailsError = detailsErrorUrl;
  1132.                 }
  1133.             }
  1134.             if(detailsErrorForm!=null) {
  1135.                 if(Costanti.POLICY_TOKEN_SOURCE_RFC6750.equals(source)) {
  1136.                     if(detailsError!=null) {
  1137.                         detailsError = detailsError+"\n";
  1138.                     }
  1139.                     else {
  1140.                         detailsError = "";
  1141.                     }
  1142.                     detailsError = detailsError + "(Form-Encoded Body Parameter) " +detailsErrorForm;
  1143.                 }
  1144.                 else {
  1145.                     detailsError = detailsErrorForm;
  1146.                 }
  1147.             }
  1148.            
  1149.            
  1150.             if(token!=null) {
  1151.                 esitoPresenzaToken.setToken(token);
  1152.                 esitoPresenzaToken.setPresente(true);
  1153.             }
  1154.             else {
  1155.                 if(detailsError!=null) {
  1156.                     esitoPresenzaToken.setDetails(detailsError);    
  1157.                 }
  1158.                 else {
  1159.                     esitoPresenzaToken.setDetails("Token non individuato tramite la configurazione indicata");  
  1160.                 }
  1161.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1162.                     esitoPresenzaToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_request, policyGestioneToken.getRealm(),
  1163.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoPresenzaToken.getDetails()));              
  1164.                 }
  1165.                 else {
  1166.                     esitoPresenzaToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_request, policyGestioneToken.getRealm(),
  1167.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoPresenzaToken.getDetails()));
  1168.                 }
  1169.             }
  1170.            
  1171.         }catch(Exception e){
  1172.             esitoPresenzaToken.setDetails(e.getMessage());
  1173.             esitoPresenzaToken.setEccezioneProcessamento(e);
  1174.         }
  1175.        
  1176.         return esitoPresenzaToken;
  1177.     }
  1178.    
  1179.    
  1180.    
  1181.    
  1182.    
  1183.    
  1184.    
  1185.     // ********* [VALIDAZIONE-TOKEN] DYNAMIC DISCOVERY ****************** */
  1186.    
  1187.     public static final String DYNAMIC_DISCOVERY_FUNCTION = "DynamicDiscovery";
  1188.    
  1189.     public static EsitoDynamicDiscovery dynamicDiscovery(Logger log, AbstractDatiInvocazione datiInvocazione,
  1190.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  1191.             EsitoPresenzaToken esitoPresenzaToken, boolean portaDelegata,
  1192.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) throws Exception {
  1193.         EsitoDynamicDiscovery esitoDynamicDiscovery = null;

  1194.         String token = esitoPresenzaToken.getToken();
  1195.        
  1196.         Cache cache = null;
  1197.         if(OpenSPCoop2Properties.getInstance().isGestioneTokenDynamicDiscoveryUseCacheConfig()) {
  1198.             cache = ConfigurazionePdDReader.getCache();
  1199.         }  
  1200.         else {
  1201.             cache = GestoreToken.cacheGestioneToken;
  1202.         }
  1203.        
  1204.         if(cache==null){
  1205.             esitoDynamicDiscovery = GestoreTokenValidazioneUtilities.dynamicDiscoveryEngine(log, datiInvocazione,
  1206.                     pddContext, protocolFactory,
  1207.                     token, portaDelegata,
  1208.                     busta, idDominio, idServizio);
  1209.         }
  1210.         else{
  1211.             String policyName = datiInvocazione.getPolicyGestioneToken().getName();
  1212.             String endpoint = datiInvocazione.getPolicyGestioneToken().getDynamicDiscoveryEndpoint();
  1213.             String funzione = DYNAMIC_DISCOVERY_FUNCTION;
  1214.            
  1215.             String tokenCache = "";
  1216.             if(OpenSPCoop2Properties.getInstance().isGestioneTokenDynamicDiscoveryKeyCacheUseToken()) {
  1217.                 tokenCache = token;
  1218.             }
  1219.             tokenCache=tokenCache+"_endpoint:"+endpoint;
  1220.            
  1221.             String keyCache = GestoreTokenValidazioneUtilities.buildCacheKeyValidazione(policyName, funzione, portaDelegata, tokenCache);

  1222.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1223.            
  1224.             org.openspcoop2.utils.cache.CacheResponse response =
  1225.                     (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  1226.             if(response != null){
  1227.                 if(response.getObject()!=null){
  1228.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1229.                     esitoDynamicDiscovery = (EsitoDynamicDiscovery) response.getObject();
  1230.                     esitoDynamicDiscovery.setInCache(true);
  1231.                 }else if(response.getException()!=null){
  1232.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1233.                     throw (Exception) response.getException();
  1234.                 }else{
  1235.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1236.                 }
  1237.             }
  1238.            
  1239.             if(esitoDynamicDiscovery==null) {
  1240.                
  1241.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1242.                 org.openspcoop2.utils.Semaphore lockDynamicDiscovery = getLockDynamicDiscovery(policyName);
  1243.                 SemaphoreLock lock = lockDynamicDiscovery.acquire("dynamicDiscovery", idTransazione);
  1244.                 try {
  1245.                    
  1246.                     response =
  1247.                         (org.openspcoop2.utils.cache.CacheResponse) cache.get(keyCache);
  1248.                     if(response != null){
  1249.                         if(response.getObject()!=null){
  1250.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1251.                             esitoDynamicDiscovery = (EsitoDynamicDiscovery) response.getObject();
  1252.                             esitoDynamicDiscovery.setInCache(true);
  1253.                         }else if(response.getException()!=null){
  1254.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1255.                             throw (Exception) response.getException();
  1256.                         }else{
  1257.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1258.                         }
  1259.                     }
  1260.    
  1261.                     if(esitoDynamicDiscovery==null) {
  1262.                         // Effettuo la query
  1263.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  1264.                         esitoDynamicDiscovery = GestoreTokenValidazioneUtilities.dynamicDiscoveryEngine(log, datiInvocazione,
  1265.                                 pddContext, protocolFactory,
  1266.                                 token, portaDelegata,
  1267.                                 busta, idDominio, idServizio);
  1268.                            
  1269.                         // Aggiungo la risposta in cache (se esiste una cache)  
  1270.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1271.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1272.                         // - impostare il noCache a true
  1273.                         esitoDynamicDiscovery.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  1274.                         if(!esitoDynamicDiscovery.isNoCache()){
  1275.                             GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  1276.                             try{    
  1277.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1278.                                 responseCache.setObject(esitoDynamicDiscovery);
  1279.                                 cache.put(keyCache,responseCache);
  1280.                             }catch(UtilsException e){
  1281.                                 GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  1282.                             }
  1283.                         }
  1284.                     }
  1285.                 }finally {
  1286.                     lockDynamicDiscovery.release(lock, "dynamicDiscovery", idTransazione);
  1287.                 }
  1288.             }
  1289.         }
  1290.        
  1291.         return esitoDynamicDiscovery;
  1292.     }
  1293.    
  1294.    
  1295.    
  1296.    
  1297.    
  1298.    
  1299.    
  1300.     // ********* [VALIDAZIONE-TOKEN] VALIDAZIONE JWT TOKEN ****************** */
  1301.    
  1302.     public static final String VALIDAZIONE_JWT_FUNCTION = "ValidazioneJWT";
  1303.        
  1304.     public static EsitoGestioneToken validazioneJWTToken(Logger log, AbstractDatiInvocazione datiInvocazione,
  1305.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  1306.             EsitoPresenzaToken esitoPresenzaToken, EsitoDynamicDiscovery esitoDynamicDiscovery, boolean portaDelegata,
  1307.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) throws Exception {
  1308.        
  1309.         EsitoGestioneToken esitoGestioneToken = null;
  1310.        
  1311.         String token = esitoPresenzaToken.getToken();
  1312.         DynamicDiscovery dynamicDiscovery = esitoDynamicDiscovery!=null ? esitoDynamicDiscovery.getDynamicDiscovery() : null;
  1313.        
  1314.         if(GestoreToken.cacheGestioneToken==null){
  1315.             esitoGestioneToken = GestoreTokenValidazioneUtilities.validazioneJWTTokenEngine(log, datiInvocazione, esitoPresenzaToken,
  1316.                     dynamicDiscovery,
  1317.                     token, portaDelegata, pddContext,
  1318.                     busta, idDominio, idServizio);
  1319.         }
  1320.         else{
  1321.             String policyName = datiInvocazione.getPolicyGestioneToken().getName();
  1322.             String funzione = VALIDAZIONE_JWT_FUNCTION;
  1323.             String keyCache = GestoreTokenValidazioneUtilities.buildCacheKeyValidazione(policyName, funzione, portaDelegata, token);

  1324.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1325.            
  1326.             org.openspcoop2.utils.cache.CacheResponse response =
  1327.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1328.             if(response != null){
  1329.                 if(response.getObject()!=null){
  1330.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1331.                     esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1332.                     esitoGestioneToken.setInCache(true);
  1333.                 }else if(response.getException()!=null){
  1334.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1335.                     throw (Exception) response.getException();
  1336.                 }else{
  1337.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1338.                 }
  1339.             }
  1340.            
  1341.             if(esitoGestioneToken==null) {
  1342.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1343.                 org.openspcoop2.utils.Semaphore lockJWT = getLockJWT(policyName);
  1344.                 SemaphoreLock lock = lockJWT.acquire("validazioneJWTToken", idTransazione);
  1345.                 try {
  1346.                    
  1347.                     response =
  1348.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1349.                     if(response != null){
  1350.                         if(response.getObject()!=null){
  1351.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1352.                             esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1353.                             esitoGestioneToken.setInCache(true);
  1354.                         }else if(response.getException()!=null){
  1355.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1356.                             throw (Exception) response.getException();
  1357.                         }else{
  1358.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1359.                         }
  1360.                     }
  1361.    
  1362.                     if(esitoGestioneToken==null) {
  1363.                         // Effettuo la query
  1364.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  1365.                         esitoGestioneToken = GestoreTokenValidazioneUtilities.validazioneJWTTokenEngine(log, datiInvocazione, esitoPresenzaToken,
  1366.                                 dynamicDiscovery,
  1367.                                 token, portaDelegata, pddContext,
  1368.                                 busta, idDominio, idServizio);
  1369.                            
  1370.                         // Aggiungo la risposta in cache (se esiste una cache)  
  1371.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1372.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1373.                         // - impostare il noCache a true
  1374.                         if(esitoGestioneToken!=null){
  1375.                             esitoGestioneToken.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  1376.                             if(!esitoGestioneToken.isNoCache()){
  1377.                                 GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  1378.                                 try{    
  1379.                                     org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1380.                                     responseCache.setObject(esitoGestioneToken);
  1381.                                     GestoreToken.cacheGestioneToken.put(keyCache,responseCache);
  1382.                                 }catch(UtilsException e){
  1383.                                     GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  1384.                                 }
  1385.                             }
  1386.                         }else{
  1387.                             throw new TokenException(getMessaggioErroreValoreEsitoNull( funzione));
  1388.                         }
  1389.                     }
  1390.                 }finally {
  1391.                     lockJWT.release(lock, "validazioneJWTToken", idTransazione);
  1392.                 }
  1393.             }
  1394.         }
  1395.        
  1396.         if(esitoGestioneToken.isValido()) {
  1397.             // ricontrollo tutte le date
  1398.             GestoreTokenValidazioneUtilities.validazioneInformazioniToken(true,
  1399.                     log, datiInvocazione, protocolFactory,
  1400.                     esitoGestioneToken, datiInvocazione.getPolicyGestioneToken(),
  1401.                     datiInvocazione.getPolicyGestioneToken().isValidazioneJWTSaveErrorInCache());
  1402.         }
  1403.        
  1404.         SecurityToken securityToken = null;
  1405.         if(
  1406.                 // esitoGestioneToken.isValido() && se non si genera comunque un security token non si hanno i json recuperati tramite la PDND
  1407.                 esitoGestioneToken.getRestSecurityToken()!=null) {
  1408.             securityToken = SecurityTokenUtilities.newSecurityToken(pddContext);
  1409.             securityToken.setAccessToken(esitoGestioneToken.getRestSecurityToken());
  1410.         }
  1411.        
  1412.         // enrich PDND Client Info
  1413.         GestoreTokenValidazioneUtilities.validazioneInformazioniTokenEnrichPDNDClientInfo(esitoGestioneToken, datiInvocazione.getPolicyGestioneToken(),
  1414.                 pddContext, protocolFactory, datiInvocazione, securityToken);
  1415.        
  1416.         return esitoGestioneToken;
  1417.     }
  1418.    
  1419.    
  1420.    
  1421.    
  1422.    
  1423.    
  1424.    
  1425.     // ********* [VALIDAZIONE-TOKEN] INTROSPECTION TOKEN ****************** */
  1426.    
  1427.     public static final String INTROSPECTION_FUNCTION = "Introspection";
  1428.    
  1429.     public static EsitoGestioneToken introspectionToken(Logger log, AbstractDatiInvocazione datiInvocazione,
  1430.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  1431.             EsitoPresenzaToken esitoPresenzaToken, EsitoDynamicDiscovery esitoDynamicDiscovery, boolean portaDelegata,
  1432.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) throws Exception {
  1433.         EsitoGestioneToken esitoGestioneToken = null;
  1434.        
  1435.         String token = esitoPresenzaToken.getToken();
  1436.         DynamicDiscovery dynamicDiscovery = esitoDynamicDiscovery!=null ? esitoDynamicDiscovery.getDynamicDiscovery() : null;
  1437.        
  1438.         if(GestoreToken.cacheGestioneToken==null){
  1439.             esitoGestioneToken = GestoreTokenValidazioneUtilities.introspectionTokenEngine(log, datiInvocazione,
  1440.                     pddContext, protocolFactory,
  1441.                     dynamicDiscovery, token, portaDelegata,
  1442.                     busta, idDominio, idServizio);
  1443.         }
  1444.         else{
  1445.             String policyName = datiInvocazione.getPolicyGestioneToken().getName();
  1446.             String funzione = INTROSPECTION_FUNCTION;
  1447.             String keyCache = GestoreTokenValidazioneUtilities.buildCacheKeyValidazione(policyName, funzione, portaDelegata, token);

  1448.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1449.            
  1450.             org.openspcoop2.utils.cache.CacheResponse response =
  1451.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1452.             if(response != null){
  1453.                 if(response.getObject()!=null){
  1454.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1455.                     esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1456.                     esitoGestioneToken.setInCache(true);
  1457.                 }else if(response.getException()!=null){
  1458.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1459.                     throw (Exception) response.getException();
  1460.                 }else{
  1461.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1462.                 }
  1463.             }
  1464.            
  1465.             if(esitoGestioneToken==null) {
  1466.                
  1467.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1468.                 org.openspcoop2.utils.Semaphore lockIntrospection = getLockIntrospection(policyName);
  1469.                 SemaphoreLock lock = lockIntrospection.acquire("introspectionToken", idTransazione);
  1470.                 try {
  1471.                    
  1472.                     response =
  1473.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1474.                     if(response != null){
  1475.                         if(response.getObject()!=null){
  1476.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1477.                             esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1478.                             esitoGestioneToken.setInCache(true);
  1479.                         }else if(response.getException()!=null){
  1480.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1481.                             throw (Exception) response.getException();
  1482.                         }else{
  1483.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1484.                         }
  1485.                     }
  1486.    
  1487.                     if(esitoGestioneToken==null) {
  1488.                         // Effettuo la query
  1489.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  1490.                         esitoGestioneToken = GestoreTokenValidazioneUtilities.introspectionTokenEngine(log, datiInvocazione,
  1491.                                 pddContext, protocolFactory,
  1492.                                 dynamicDiscovery, token, portaDelegata,
  1493.                                 busta, idDominio, idServizio);
  1494.                            
  1495.                         // Aggiungo la risposta in cache (se esiste una cache)  
  1496.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1497.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1498.                         // - impostare il noCache a true
  1499.                         esitoGestioneToken.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  1500.                         if(!esitoGestioneToken.isNoCache()){
  1501.                             GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  1502.                             try{    
  1503.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1504.                                 responseCache.setObject(esitoGestioneToken);
  1505.                                 GestoreToken.cacheGestioneToken.put(keyCache,responseCache);
  1506.                             }catch(UtilsException e){
  1507.                                 GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  1508.                             }
  1509.                         }
  1510.                     }
  1511.                 }finally {
  1512.                     lockIntrospection.release(lock, "introspectionToken", idTransazione);
  1513.                 }
  1514.             }
  1515.         }
  1516.        
  1517.         if(esitoGestioneToken.isValido()) {
  1518.             // ricontrollo tutte le date
  1519.             GestoreTokenValidazioneUtilities.validazioneInformazioniToken(false,
  1520.                     log, datiInvocazione, protocolFactory,
  1521.                     esitoGestioneToken, datiInvocazione.getPolicyGestioneToken(),
  1522.                     datiInvocazione.getPolicyGestioneToken().isIntrospectionSaveErrorInCache());
  1523.         }
  1524.        
  1525.         return esitoGestioneToken;
  1526.     }
  1527.    
  1528.    
  1529.    
  1530.    
  1531.    
  1532.    
  1533.     // ********* [VALIDAZIONE-TOKEN] USER INFO TOKEN ****************** */
  1534.    
  1535.     public static final String USERINFO_FUNCTION = "UserInfo";
  1536.    
  1537.     public static EsitoGestioneToken userInfoToken(Logger log, AbstractDatiInvocazione datiInvocazione,
  1538.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  1539.             EsitoPresenzaToken esitoPresenzaToken, EsitoDynamicDiscovery esitoDynamicDiscovery, boolean portaDelegata,
  1540.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) throws Exception {
  1541.         EsitoGestioneToken esitoGestioneToken = null;
  1542.        
  1543.         String token = esitoPresenzaToken.getToken();
  1544.         DynamicDiscovery dynamicDiscovery = esitoDynamicDiscovery!=null ? esitoDynamicDiscovery.getDynamicDiscovery() : null;
  1545.        
  1546.         if(GestoreToken.cacheGestioneToken==null){
  1547.             esitoGestioneToken = GestoreTokenValidazioneUtilities.userInfoTokenEngine(log, datiInvocazione,
  1548.                     pddContext, protocolFactory,
  1549.                     dynamicDiscovery, token, portaDelegata,
  1550.                     busta, idDominio, idServizio);
  1551.         }
  1552.         else{
  1553.             String policyName = datiInvocazione.getPolicyGestioneToken().getName();
  1554.             String funzione = USERINFO_FUNCTION;
  1555.             String keyCache = GestoreTokenValidazioneUtilities.buildCacheKeyValidazione(policyName, funzione, portaDelegata, token);

  1556.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1557.            
  1558.             org.openspcoop2.utils.cache.CacheResponse response =
  1559.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1560.             if(response != null){
  1561.                 if(response.getObject()!=null){
  1562.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1563.                     esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1564.                     esitoGestioneToken.setInCache(true);
  1565.                 }else if(response.getException()!=null){
  1566.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1567.                     throw (Exception) response.getException();
  1568.                 }else{
  1569.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1570.                 }
  1571.             }
  1572.            
  1573.             if(esitoGestioneToken==null) {
  1574.                 String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1575.                 org.openspcoop2.utils.Semaphore lockUserInfo = getLockUserInfo(policyName);
  1576.                 SemaphoreLock lock = lockUserInfo.acquire("userInfoToken", idTransazione);
  1577.                 try {
  1578.                    
  1579.                     response =
  1580.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1581.                     if(response != null){
  1582.                         if(response.getObject()!=null){
  1583.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1584.                             esitoGestioneToken = (EsitoGestioneToken) response.getObject();
  1585.                             esitoGestioneToken.setInCache(true);
  1586.                         }else if(response.getException()!=null){
  1587.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1588.                             throw (Exception) response.getException();
  1589.                         }else{
  1590.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1591.                         }
  1592.                     }
  1593.    
  1594.                     if(esitoGestioneToken==null) {
  1595.                         // Effettuo la query
  1596.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  1597.                         esitoGestioneToken = GestoreTokenValidazioneUtilities.userInfoTokenEngine(log, datiInvocazione,
  1598.                                 pddContext, protocolFactory,
  1599.                                 dynamicDiscovery, token, portaDelegata,
  1600.                                 busta, idDominio, idServizio);
  1601.                            
  1602.                         // Aggiungo la risposta in cache (se esiste una cache)  
  1603.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1604.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1605.                         // - impostare il noCache a true
  1606.                         esitoGestioneToken.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  1607.                         if(!esitoGestioneToken.isNoCache()){
  1608.                             GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  1609.                             try{    
  1610.                                 org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1611.                                 responseCache.setObject(esitoGestioneToken);
  1612.                                 GestoreToken.cacheGestioneToken.put(keyCache,responseCache);
  1613.                             }catch(UtilsException e){
  1614.                                 GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  1615.                             }
  1616.                         }
  1617.                     }
  1618.                 }finally {
  1619.                     lockUserInfo.release(lock, "userInfoToken", idTransazione);
  1620.                 }
  1621.             }
  1622.         }
  1623.        
  1624.         if(esitoGestioneToken.isValido()) {
  1625.             // ricontrollo tutte le date
  1626.             GestoreTokenValidazioneUtilities.validazioneInformazioniToken(false,
  1627.                     log, datiInvocazione, protocolFactory,
  1628.                     esitoGestioneToken, datiInvocazione.getPolicyGestioneToken(),
  1629.                     datiInvocazione.getPolicyGestioneToken().isUserInfoSaveErrorInCache());
  1630.         }
  1631.        
  1632.         return esitoGestioneToken;
  1633.     }
  1634.    
  1635.    
  1636.    
  1637.    
  1638.    
  1639.    
  1640.    
  1641.    
  1642.     // ********* [VALIDAZIONE-TOKEN] FORWARD TOKEN ****************** */
  1643.    
  1644.     public static void forwardToken(Logger log, String idTransazione, AbstractDatiInvocazione datiInvocazione, EsitoPresenzaToken esitoPresenzaToken,
  1645.             EsitoGestioneToken esitoValidazioneJWT, EsitoGestioneToken esitoIntrospection, EsitoGestioneToken esitoUserInfo,
  1646.             InformazioniToken informazioniTokenNormalizzate,
  1647.             boolean portaDelegata,
  1648.             PdDContext pddContext, Busta busta) throws Exception {
  1649.        
  1650.         if(datiInvocazione==null) {
  1651.             throw new CoreException("Dati invocazioni is null");
  1652.         }
  1653.        
  1654.         PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  1655.            
  1656.         TokenForward tokenForward = new TokenForward();
  1657.         String token = esitoPresenzaToken.getToken();
  1658.        
  1659.         boolean trasparente = false;
  1660.         String forwardTrasparenteMode = null;
  1661.         String forwardTrasparenteModeHeader = null;
  1662.         String forwardTrasparenteModeUrl = null;
  1663.         if(policyGestioneToken.isForwardToken()) {
  1664.             trasparente = policyGestioneToken.isForwardTokenTrasparente();
  1665.             if(trasparente) {
  1666.                 forwardTrasparenteMode = policyGestioneToken.getForwardTokenTrasparenteMode();
  1667.                 if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_AS_RECEIVED.equals(forwardTrasparenteMode)) {
  1668.                     forwardTrasparenteModeHeader = esitoPresenzaToken.getHeaderHttp();
  1669.                     forwardTrasparenteModeUrl = esitoPresenzaToken.getPropertyUrl();
  1670.                 }
  1671.                 else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_RFC6750_HEADER.equals(forwardTrasparenteMode)) {
  1672.                     forwardTrasparenteModeHeader = HttpConstants.AUTHORIZATION;
  1673.                 }
  1674.                 else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_RFC6750_URL.equals(forwardTrasparenteMode)) {
  1675.                     forwardTrasparenteModeUrl = Costanti.RFC6750_URI_QUERY_PARAMETER_ACCESS_TOKEN;
  1676.                 }
  1677.                 else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_CUSTOM_HEADER.equals(forwardTrasparenteMode)) {
  1678.                     forwardTrasparenteModeHeader = policyGestioneToken.getForwardTokenTrasparenteModeCustomHeader();
  1679.                 }
  1680.                 else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_CUSTOM_URL.equals(forwardTrasparenteMode)) {
  1681.                     forwardTrasparenteModeUrl = policyGestioneToken.getForwardTokenTrasparenteModeCustomUrl();
  1682.                 }
  1683.             }
  1684.         }
  1685.        
  1686.         boolean infoRaccolte = false;
  1687.         String forwardInformazioniRaccolteMode = null;
  1688.         Properties jwtSecurity = null;
  1689.         boolean encodeBase64 = false;
  1690.         boolean forwardValidazioneJWT = false;  
  1691.         String forwardValidazioneJWTMode = null;
  1692.         String forwardValidazioneJWTName = null;
  1693.         boolean forwardIntrospection = false;  
  1694.         String forwardIntrospectionMode = null;
  1695.         String forwardIntrospectionName = null;
  1696.         boolean forwardUserInfo = false;    
  1697.         String forwardUserInfoMode = null;
  1698.         String forwardUserInfoName = null;
  1699.         if(policyGestioneToken.isForwardToken()) {
  1700.             infoRaccolte = policyGestioneToken.isForwardTokenInformazioniRaccolte();
  1701.             if(infoRaccolte) {
  1702.                 forwardInformazioniRaccolteMode = policyGestioneToken.getForwardTokenInformazioniRaccolteMode();
  1703.                 encodeBase64 = policyGestioneToken.isForwardTokenInformazioniRaccolteEncodeBase64();
  1704.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_JWS.equals(forwardInformazioniRaccolteMode) ||
  1705.                         Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWS.equals(forwardInformazioniRaccolteMode)) {
  1706.                     jwtSecurity = policyGestioneToken.getProperties().get(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_SIGNATURE_PROP_REF_ID);
  1707.                 }
  1708.                 else if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWE.equals(forwardInformazioniRaccolteMode)) {
  1709.                     jwtSecurity = policyGestioneToken.getProperties().get(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_ENCRYP_PROP_REF_ID);
  1710.                 }
  1711.                
  1712.                 if(jwtSecurity!=null) {
  1713.                     boolean throwError = true;
  1714.                     Map<String,Object> dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(busta, datiInvocazione.getRequestInfo(), pddContext, log);
  1715.                     JOSEUtils.injectKeystore(datiInvocazione.getRequestInfo(), dynamicMap, jwtSecurity, log, throwError); // serve per leggere il keystore dalla cache
  1716.                 }
  1717.                
  1718.                 forwardValidazioneJWT = policyGestioneToken.isForwardTokenInformazioniRaccolteValidazioneJWT();
  1719.                 if(forwardValidazioneJWT) {
  1720.                     forwardValidazioneJWTMode = policyGestioneToken.getForwardTokenInformazioniRaccolteValidazioneJWTMode();
  1721.                     if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardValidazioneJWTMode)) {
  1722.                         forwardValidazioneJWTName = policyGestioneToken.getForwardTokenInformazioniRaccolteValidazioneJWTModeHeaderName();
  1723.                     }
  1724.                     else {
  1725.                         forwardValidazioneJWTName = policyGestioneToken.getForwardTokenInformazioniRaccolteValidazioneJWTModeQueryParameterName();
  1726.                     }
  1727.                 }
  1728.                
  1729.                 forwardIntrospection = policyGestioneToken.isForwardTokenInformazioniRaccolteIntrospection();
  1730.                 if(forwardIntrospection) {
  1731.                     forwardIntrospectionMode = policyGestioneToken.getForwardTokenInformazioniRaccolteIntrospectionMode();
  1732.                     if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardIntrospectionMode)) {
  1733.                         forwardIntrospectionName = policyGestioneToken.getForwardTokenInformazioniRaccolteIntrospectionModeHeaderName();
  1734.                     }
  1735.                     else {
  1736.                         forwardIntrospectionName = policyGestioneToken.getForwardTokenInformazioniRaccolteIntrospectionModeQueryParameterName();
  1737.                     }
  1738.                 }
  1739.                
  1740.                 forwardUserInfo = policyGestioneToken.isForwardTokenInformazioniRaccolteUserInfo();
  1741.                 if(forwardUserInfo) {
  1742.                     forwardUserInfoMode = policyGestioneToken.getForwardTokenInformazioniRaccolteUserInfoMode();
  1743.                     if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardUserInfoMode)) {
  1744.                         forwardUserInfoName = policyGestioneToken.getForwardTokenInformazioniRaccolteUserInfoModeHeaderName();
  1745.                     }
  1746.                     else {
  1747.                         forwardUserInfoName = policyGestioneToken.getForwardTokenInformazioniRaccolteUserInfoModeQueryParameterName();
  1748.                     }
  1749.                 }
  1750.             }
  1751.         }
  1752.        
  1753.         // Elimino token ricevuto
  1754.         boolean delete = GestoreTokenValidazioneUtilities.deleteTokenReceived(datiInvocazione, esitoPresenzaToken, trasparente, forwardTrasparenteModeHeader, forwardTrasparenteModeUrl);
  1755.         boolean soap = datiInvocazione!=null && datiInvocazione.getMessage()!=null && org.openspcoop2.message.constants.ServiceBinding.SOAP.equals(datiInvocazione.getMessage().getServiceBinding());
  1756.        
  1757.         if(trasparente &&
  1758.                 (
  1759.                         delete // eventualmente effettuo il forward di altri header
  1760.                         ||
  1761.                         soap // anche gli header originali non vengono inoltrati
  1762.                 )
  1763.         ) {
  1764.            
  1765.             // Forward trasparente
  1766.            
  1767.             // la delete ha tenuto conto dell'opzione di forward prima di eliminare
  1768.             GestoreTokenValidazioneUtilities.forwardTokenTrasparenteEngine(token, esitoPresenzaToken, tokenForward, forwardTrasparenteMode, forwardTrasparenteModeHeader, forwardTrasparenteModeUrl);
  1769.         }
  1770.        
  1771.         if(infoRaccolte) {
  1772.            
  1773.             // Forward informazioni raccolte
  1774.            
  1775.             GestoreTokenValidazioneUtilities.forwardInfomazioniRaccolteEngine(portaDelegata, idTransazione, tokenForward,
  1776.                     esitoValidazioneJWT, esitoIntrospection, esitoUserInfo,
  1777.                     informazioniTokenNormalizzate,
  1778.                     forwardInformazioniRaccolteMode, jwtSecurity, encodeBase64,
  1779.                     forwardValidazioneJWT, forwardValidazioneJWTMode, forwardValidazioneJWTName,
  1780.                     forwardIntrospection, forwardIntrospectionMode, forwardIntrospectionName,
  1781.                     forwardUserInfo, forwardUserInfoMode, forwardUserInfoName);
  1782.            
  1783.         }
  1784.        
  1785.         // Imposto token forward nel messaggio
  1786.         if(tokenForward.getUrl().size()>0 || tokenForward.getTrasporto().size()>0) {
  1787.             datiInvocazione.getMessage().addContextProperty(Costanti.MSG_CONTEXT_TOKEN_FORWARD, tokenForward);
  1788.         }

  1789.     }

  1790.     public static List<InformazioniToken> getInformazioniTokenValide(EsitoGestioneToken esitoValidazioneJWT, EsitoGestioneToken esitoIntrospection, EsitoGestioneToken esitoUserInfo){
  1791.         List<InformazioniToken> list = new ArrayList<>();
  1792.         if(esitoValidazioneJWT!=null && esitoValidazioneJWT.isValido() && esitoValidazioneJWT.getInformazioniToken()!=null) {
  1793.             list.add(esitoValidazioneJWT.getInformazioniToken());
  1794.         }
  1795.         if(esitoIntrospection!=null && esitoIntrospection.isValido() && esitoIntrospection.getInformazioniToken()!=null) {
  1796.             list.add(esitoIntrospection.getInformazioniToken());
  1797.         }
  1798.         if(esitoUserInfo!=null && esitoUserInfo.isValido() && esitoUserInfo.getInformazioniToken()!=null) {
  1799.             list.add(esitoUserInfo.getInformazioniToken());
  1800.         }
  1801.         return list;
  1802.     }
  1803.    
  1804.     public static List<InformazioniToken> getInformazioniTokenNonValide(EsitoGestioneToken esitoValidazioneJWT, EsitoGestioneToken esitoIntrospection, EsitoGestioneToken esitoUserInfo){
  1805.        
  1806.         // A differenza del metodo sopra non si controlla che il token sia valido.
  1807.        
  1808.         List<InformazioniToken> list = new ArrayList<>();
  1809.         if(esitoValidazioneJWT!=null && esitoValidazioneJWT.getInformazioniToken()!=null) {
  1810.             list.add(esitoValidazioneJWT.getInformazioniToken());
  1811.         }
  1812.         if(esitoIntrospection!=null && esitoIntrospection.getInformazioniToken()!=null) {
  1813.             list.add(esitoIntrospection.getInformazioniToken());
  1814.         }
  1815.         if(esitoUserInfo!=null && esitoUserInfo.getInformazioniToken()!=null) {
  1816.             list.add(esitoUserInfo.getInformazioniToken());
  1817.         }
  1818.         return list;
  1819.     }
  1820.    
  1821.     public static InformazioniToken normalizeInformazioniToken(List<InformazioniToken> list) throws Exception {
  1822.         if(list.size()==1) {
  1823.             return list.get(0);
  1824.         }
  1825.         else {
  1826.             return new InformazioniToken(OpenSPCoop2Properties.getInstance().isGestioneTokenSaveSourceTokenInfo(), list.toArray(new InformazioniToken[1]));
  1827.         }
  1828.     }
  1829.    
  1830.    
  1831.    
  1832.    
  1833.    
  1834.    
  1835.    
  1836.    
  1837.    
  1838.    
  1839.     // ********* [NEGOZIAZIONE-TOKEN] VALIDAZIONE CONFIGURAZIONE ****************** */
  1840.    
  1841.     public static void validazioneConfigurazione(PolicyNegoziazioneToken policyNegoziazioneToken) throws ProviderException, ProviderValidationException {
  1842.         NegoziazioneTokenProvider p = new NegoziazioneTokenProvider();
  1843.         p.validate(policyNegoziazioneToken.getProperties());
  1844.     }
  1845.    
  1846.    
  1847.     // ********* [NEGOZIAZIONE-TOKEN] ENDPOINT TOKEN ****************** */
  1848.    
  1849.     public static final String RETRIEVE_FUNCTION = "Negoziazione";
  1850.        
  1851.     public static EsitoNegoziazioneToken endpointToken(boolean debug, Logger log, PolicyNegoziazioneToken policyNegoziazioneToken,
  1852.             Busta busta, RequestInfo requestInfo, TipoPdD tipoPdD, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  1853.             PdDContext pddContext, IProtocolFactory<?> protocolFactory) throws Exception {
  1854.         return endpointTokenEngine(debug, log, policyNegoziazioneToken,
  1855.                 busta, requestInfo, tipoPdD, idModulo, pa, pd,
  1856.                 pddContext,  protocolFactory,
  1857.                 false, null,
  1858.                 null);
  1859.     }
  1860.     private static EsitoNegoziazioneToken endpointTokenEngine(boolean debug, Logger log, PolicyNegoziazioneToken policyNegoziazioneToken,
  1861.             Busta busta, RequestInfo requestInfo, TipoPdD tipoPdD, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  1862.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  1863.             boolean rinegozia, InformazioniNegoziazioneToken previousToken,
  1864.             InformazioniNegoziazioneToken_DatiRichiesta datiRichiesta) throws Exception {
  1865.         EsitoNegoziazioneToken esitoNegoziazioneToken = null;
  1866.         boolean riavviaNegoziazione = rinegozia;
  1867.         riavviaNegoziazione = false;
  1868.        
  1869.         IState state = null;
  1870.         boolean delegata = TipoPdD.DELEGATA.equals(tipoPdD);
  1871.         IDSoggetto idDominio = null;
  1872.         IDServizio idServizio = null;
  1873.         if(busta!=null) {
  1874.             if(delegata) {
  1875.                 if(busta.getTipoMittente()!=null && busta.getMittente()!=null) {
  1876.                     idDominio = new IDSoggetto(busta.getTipoMittente(), busta.getMittente());
  1877.                 }
  1878.             }
  1879.             else {
  1880.                 if(busta.getTipoDestinatario()!=null && busta.getDestinatario()!=null) {
  1881.                     idDominio = new IDSoggetto(busta.getTipoDestinatario(), busta.getDestinatario());
  1882.                 }
  1883.             }
  1884.             if(busta.getTipoDestinatario()!=null && busta.getDestinatario()!=null &&
  1885.                     busta.getTipoServizio()!=null && busta.getServizio()!=null && busta.getVersioneServizio()!=null) {
  1886.                 idServizio = IDServizioFactory.getInstance().getIDServizioFromValues(busta.getTipoServizio(), busta.getServizio(),
  1887.                         busta.getTipoDestinatario(), busta.getDestinatario(),
  1888.                         busta.getVersioneServizio());  
  1889.             }
  1890.         }
  1891.        
  1892.         String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  1893.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  1894.         if(datiRichiesta==null && op2Properties.isGestioneRetrieveTokenSaveAsTokenInfoSaveSourceRequest()) {
  1895.             datiRichiesta = new InformazioniNegoziazioneToken_DatiRichiesta();
  1896.             datiRichiesta.setPolicy(policyNegoziazioneToken.getName());
  1897.             datiRichiesta.setTransactionId(idTransazione);
  1898.             if(op2Properties.isGestioneRetrieveTokenSaveAsTokenInfoSaveSourceRequestDate()) {
  1899.                 datiRichiesta.setPrepareRequest(DateManager.getDate());
  1900.             }
  1901.         }
  1902.        
  1903.         Map<String, Object> dynamicMap = GestoreTokenNegoziazioneUtilities.buildDynamicNegoziazioneTokenMap(busta, requestInfo, pddContext, log);
  1904.         NegoziazioneTokenDynamicParameters dynamicParameters = new NegoziazioneTokenDynamicParameters(dynamicMap,
  1905.                 pddContext, requestInfo, busta, state, protocolFactory,
  1906.                 policyNegoziazioneToken);
  1907.        
  1908.         if(GestoreToken.cacheGestioneToken==null){
  1909.             esitoNegoziazioneToken = GestoreTokenNegoziazioneUtilities.endpointTokenEngine(debug, log, policyNegoziazioneToken,
  1910.                     busta, requestInfo, tipoPdD,
  1911.                     dynamicParameters, protocolFactory,
  1912.                     state, delegata, idModulo, pa, pd,
  1913.                     idDominio, idServizio,
  1914.                     previousToken,
  1915.                     datiRichiesta);
  1916.            
  1917.             if(esitoNegoziazioneToken!=null && esitoNegoziazioneToken.isValido()) {
  1918.                 // ricontrollo tutte le date (l'ho appena preso, dovrebbero essere buone)
  1919.                 boolean checkPerRinegoziazione = false;
  1920.                 GestoreTokenNegoziazioneUtilities.validazioneInformazioniNegoziazioneToken(checkPerRinegoziazione, esitoNegoziazioneToken,  
  1921.                         policyNegoziazioneToken.isSaveErrorInCache());
  1922.             }
  1923.            
  1924.         }
  1925.         else{
  1926.             String policyName = policyNegoziazioneToken.getName();
  1927.             String funzione = RETRIEVE_FUNCTION;
  1928.             String keyCache = GestoreTokenNegoziazioneUtilities.buildCacheKeyNegoziazione(policyName, funzione, delegata, dynamicParameters);

  1929.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  1930.            
  1931.             org.openspcoop2.utils.cache.CacheResponse response =
  1932.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1933.             if(response != null){
  1934.                 if(response.getObject()!=null){
  1935.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1936.                     esitoNegoziazioneToken = (EsitoNegoziazioneToken) response.getObject();
  1937.                     esitoNegoziazioneToken.setInCache(true);
  1938.                 }else if(response.getException()!=null){
  1939.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1940.                     throw (Exception) response.getException();
  1941.                 }else{
  1942.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1943.                 }
  1944.             }
  1945.            
  1946.             if(esitoNegoziazioneToken==null) {
  1947.                 org.openspcoop2.utils.Semaphore lockNegoziazione = getLockNegoziazione(policyName);
  1948.                 SemaphoreLock lock = lockNegoziazione.acquire("endpointToken", idTransazione);
  1949.                 try {
  1950.                    
  1951.                     response =
  1952.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  1953.                     if(response != null){
  1954.                         if(response.getObject()!=null){
  1955.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  1956.                             esitoNegoziazioneToken = (EsitoNegoziazioneToken) response.getObject();
  1957.                             esitoNegoziazioneToken.setInCache(true);
  1958.                         }else if(response.getException()!=null){
  1959.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  1960.                             throw (Exception) response.getException();
  1961.                         }else{
  1962.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  1963.                         }
  1964.                     }
  1965.    
  1966.                     if(esitoNegoziazioneToken==null) {
  1967.                         // Effettuo la query
  1968.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  1969.                         esitoNegoziazioneToken = GestoreTokenNegoziazioneUtilities.endpointTokenEngine(debug, log, policyNegoziazioneToken,
  1970.                                 busta, requestInfo, tipoPdD,
  1971.                                 dynamicParameters, protocolFactory,
  1972.                                 state, delegata, idModulo, pa, pd,
  1973.                                 idDominio, idServizio,
  1974.                                 previousToken,
  1975.                                 datiRichiesta);
  1976.                            
  1977.                         // Aggiungo la risposta in cache (se esiste una cache)  
  1978.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  1979.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  1980.                         // - impostare il noCache a true
  1981.                         if(esitoNegoziazioneToken!=null){ // altrimenti lo mettero' in cache al giro dopo.
  1982.                             esitoNegoziazioneToken.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  1983.                             if(!esitoNegoziazioneToken.isNoCache()){
  1984.                                 GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  1985.                                 try{    
  1986.                                     org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  1987.                                     responseCache.setObject(esitoNegoziazioneToken);
  1988.                                     GestoreToken.cacheGestioneToken.put(keyCache,responseCache);
  1989.                                 }catch(UtilsException e){
  1990.                                     GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  1991.                                 }
  1992.                             }
  1993.                         }else{
  1994.                             throw new TokenException(getMessaggioErroreValoreEsitoNull( funzione));
  1995.                         }
  1996.                        
  1997.                         if(esitoNegoziazioneToken.isValido()) {
  1998.                             // ricontrollo tutte le date (l'ho appena preso, dovrebbero essere buone)
  1999.                             boolean checkPerRinegoziazione = false;
  2000.                             GestoreTokenNegoziazioneUtilities.validazioneInformazioniNegoziazioneToken(checkPerRinegoziazione, esitoNegoziazioneToken,  
  2001.                                     policyNegoziazioneToken.isSaveErrorInCache());
  2002.                         }
  2003.                     }
  2004.                     else {
  2005.                    
  2006.                         // l'ho preso in cache
  2007.                        
  2008.                         if(esitoNegoziazioneToken.isValido()) {
  2009.                             // controllo la data qua
  2010.                             boolean checkPerRinegoziazione = true;
  2011.                             GestoreTokenNegoziazioneUtilities.validazioneInformazioniNegoziazioneToken(checkPerRinegoziazione, esitoNegoziazioneToken,  
  2012.                                     policyNegoziazioneToken.isSaveErrorInCache());
  2013.                             if(!esitoNegoziazioneToken.isValido() && !esitoNegoziazioneToken.isDateValide()) {
  2014.                                 // DEVO riavviare la negoziazione poichè è scaduto
  2015.                                 GestoreToken.cacheGestioneToken.remove(keyCache);
  2016.                                 riavviaNegoziazione = true;
  2017.                                 /** System.out.println("Riavvia negoziazione"); */
  2018.                             }
  2019.                         }
  2020.                        
  2021.                     }
  2022.                    
  2023.                 }finally {
  2024.                     // fine synchronized
  2025.                     lockNegoziazione.release(lock, "endpointToken", idTransazione);
  2026.                 }
  2027.             }
  2028.             else {
  2029.                
  2030.                 // l'ho preso in cache
  2031.                
  2032.                 if(esitoNegoziazioneToken.isValido()) {
  2033.                     // controllo la data qua
  2034.                     boolean checkPerRinegoziazione = true;
  2035.                     GestoreTokenNegoziazioneUtilities.validazioneInformazioniNegoziazioneToken(checkPerRinegoziazione, esitoNegoziazioneToken,  
  2036.                             policyNegoziazioneToken.isSaveErrorInCache());
  2037.                     if(!esitoNegoziazioneToken.isValido() && !esitoNegoziazioneToken.isDateValide()) {
  2038.                        
  2039.                         org.openspcoop2.utils.Semaphore lockNegoziazione = getLockNegoziazione(policyName);
  2040.                         SemaphoreLock lock = lockNegoziazione.acquire("removeToken", idTransazione);
  2041.                         try {
  2042.                             // DEVO riavviare la negoziazione poichè è scaduto
  2043.                             GestoreToken.cacheGestioneToken.remove(keyCache);
  2044.                             riavviaNegoziazione = true;
  2045.                             /** System.out.println("Riavvia negoziazione"); */
  2046.                         }finally {
  2047.                             // fine synchronized
  2048.                             lockNegoziazione.release(lock, "removeToken", idTransazione);
  2049.                         }
  2050.                     }
  2051.                 }
  2052.                
  2053.             }
  2054.         }
  2055.        
  2056.         if(riavviaNegoziazione) {
  2057.             return endpointTokenEngine(debug, log, policyNegoziazioneToken,
  2058.                     busta, requestInfo, tipoPdD, idModulo, pa, pd,
  2059.                     pddContext, protocolFactory,
  2060.                     riavviaNegoziazione, esitoNegoziazioneToken.getInformazioniNegoziazioneToken(),// refresh
  2061.                     datiRichiesta);
  2062.         }
  2063.        
  2064.         try {
  2065.             if(idTransazione!=null) {
  2066.                 Transaction t = TransactionContext.getTransaction(idTransazione);
  2067.                 if(esitoNegoziazioneToken!=null) {
  2068.                     t.setInformazioniNegoziazioneToken(esitoNegoziazioneToken.getInformazioniNegoziazioneToken());
  2069.                 }
  2070.             }
  2071.         }catch(Exception t) {
  2072.             // ignore
  2073.         }
  2074.        
  2075.         return esitoNegoziazioneToken;
  2076.     }
  2077.    

  2078.    
  2079.    
  2080.    
  2081.    
  2082.    
  2083.    
  2084.    
  2085.    
  2086.    
  2087.    
  2088.    
  2089.     // ********* [ATTRIBUTE AUTHORITY] VALIDAZIONE CONFIGURAZIONE ****************** */
  2090.    
  2091.     public static void validazioneConfigurazione(PolicyAttributeAuthority policyAttributeAuthority) throws ProviderException, ProviderValidationException {
  2092.         AttributeAuthorityProvider p = new AttributeAuthorityProvider();
  2093.         p.validate(policyAttributeAuthority.getProperties());
  2094.     }
  2095.    
  2096.    
  2097.     // ********* [ATTRIBUTE AUTHORITY] ENDPOINT TOKEN ****************** */
  2098.    
  2099.     public static final String ATTRIBUTE_AUTHORITY_FUNCTION = "AttributeAuthority";
  2100.    
  2101.     public static EsitoRecuperoAttributi readAttributes(Logger log, org.openspcoop2.pdd.core.token.attribute_authority.AbstractDatiInvocazione datiInvocazione,
  2102.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  2103.             boolean portaDelegata,
  2104.             IDSoggetto idDominio, IDServizio idServizio) throws Exception {
  2105.         EsitoRecuperoAttributi esitoRecuperoAttributi = null;
  2106.         boolean riavviaNegoziazione = false;
  2107.            
  2108.         PolicyAttributeAuthority policyAttributeAuthority = datiInvocazione.getPolicyAttributeAuthority();
  2109.         OpenSPCoop2Message message = datiInvocazione.getMessage();
  2110.         Busta busta = datiInvocazione.getBusta();
  2111.         RequestInfo requestInfo = datiInvocazione.getRequestInfo();
  2112.        
  2113.         Map<String, Object> dynamicMap = GestoreTokenAttributeAuthorityUtilities.buildDynamicAAMap(message, busta, requestInfo, pddContext, log,
  2114.                 policyAttributeAuthority.getName(), datiInvocazione);
  2115.         AttributeAuthorityDynamicParameters dynamicParameters = new AttributeAuthorityDynamicParameters(dynamicMap, pddContext, requestInfo, policyAttributeAuthority);
  2116.        
  2117.         ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  2118.        
  2119.         PortaApplicativa pa = null;
  2120.         PortaDelegata pd = null;
  2121.         if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  2122.             pa = ((DatiInvocazionePortaApplicativa)datiInvocazione).getPa();
  2123.         }
  2124.         else if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  2125.             pd = ((DatiInvocazionePortaDelegata)datiInvocazione).getPd();
  2126.         }
  2127.        
  2128.         if(GestoreToken.cacheAttributeAuthority==null){
  2129.                        
  2130.             boolean addIdAndDate = true;
  2131.             String request = GestoreTokenAttributeAuthorityUtilities.buildDynamicAARequest(configurazionePdDManager,  
  2132.                     protocolFactory, requestInfo,
  2133.                     policyAttributeAuthority, dynamicParameters, addIdAndDate);
  2134.            
  2135.             esitoRecuperoAttributi = GestoreTokenAttributeAuthorityUtilities.readAttributes(log, policyAttributeAuthority,
  2136.                     protocolFactory,
  2137.                     dynamicParameters,
  2138.                     request, portaDelegata,
  2139.                     pddContext, datiInvocazione.getBusta(),
  2140.                     datiInvocazione.getIdModulo(), pa, pd,
  2141.                     datiInvocazione.getState(),
  2142.                     idDominio, idServizio,
  2143.                     requestInfo);
  2144.            
  2145.             if(esitoRecuperoAttributi!=null && esitoRecuperoAttributi.isValido()) {
  2146.                 // ricontrollo tutte le date (l'ho appena preso, dovrebbero essere buone)
  2147.                 GestoreTokenAttributeAuthorityUtilities.validazioneInformazioniAttributiRecuperati(esitoRecuperoAttributi, policyAttributeAuthority,
  2148.                         policyAttributeAuthority.isSaveErrorInCache(),
  2149.                         dynamicParameters);
  2150.             }
  2151.            
  2152.         }
  2153.         else{
  2154.             String funzione = ATTRIBUTE_AUTHORITY_FUNCTION;
  2155.            
  2156.             boolean addIdAndDate = true;
  2157.            
  2158.             // Aggiungo anche la richiesta poichè può venire costruita con freemarker o template e quindi può essere dinamica a sua volta (non considero però le date)
  2159.             String requestKeyCache = GestoreTokenAttributeAuthorityUtilities.buildDynamicAARequest(configurazionePdDManager,
  2160.                     protocolFactory, requestInfo,
  2161.                     policyAttributeAuthority, dynamicParameters, !addIdAndDate);
  2162.            
  2163.             String aaName = policyAttributeAuthority.getName();
  2164.             String keyCache = GestoreTokenAttributeAuthorityUtilities.buildCacheKeyRecuperoAttributi(aaName, funzione, portaDelegata, dynamicParameters, requestKeyCache);

  2165.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  2166.            
  2167.             org.openspcoop2.utils.cache.CacheResponse response =
  2168.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheAttributeAuthority.get(keyCache);
  2169.             if(response != null){
  2170.                 if(response.getObject()!=null){
  2171.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  2172.                     esitoRecuperoAttributi = (EsitoRecuperoAttributi) response.getObject();
  2173.                     esitoRecuperoAttributi.setInCache(true);
  2174.                 }else if(response.getException()!=null){
  2175.                     GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  2176.                     throw (Exception) response.getException();
  2177.                 }else{
  2178.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  2179.                 }
  2180.             }
  2181.            
  2182.             String idTransazione = (pddContext!=null && pddContext.containsKey(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE)) ? PdDContext.getValue(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE, pddContext) : null;
  2183.            
  2184.             if(esitoRecuperoAttributi==null) {
  2185.            
  2186.                 org.openspcoop2.utils.Semaphore lockAttributeAuthority = getLockAttributeAuthority(aaName);
  2187.                 SemaphoreLock lock = lockAttributeAuthority.acquire("readAttributes", idTransazione);
  2188.                 try {
  2189.                    
  2190.                     response =
  2191.                         (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheAttributeAuthority.get(keyCache);
  2192.                     if(response != null){
  2193.                         if(response.getObject()!=null){
  2194.                             GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  2195.                             esitoRecuperoAttributi = (EsitoRecuperoAttributi) response.getObject();
  2196.                             esitoRecuperoAttributi.setInCache(true);
  2197.                         }else if(response.getException()!=null){
  2198.                             GestoreToken.loggerDebug(GestoreToken.getMessageEccezioneInCache(response, keyCache, funzione));
  2199.                             throw (Exception) response.getException();
  2200.                         }else{
  2201.                             GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  2202.                         }
  2203.                     }
  2204.    
  2205.                     if(esitoRecuperoAttributi==null) {
  2206.                         // Effettuo la query
  2207.                         GestoreToken.loggerDebug(getPrefixOggettoConChiave(keyCache)+getSuffixEseguiOperazione(funzione));
  2208.                        
  2209.                         String request = null;
  2210.                         if(policyAttributeAuthority.isRequestDynamicPayloadJwt()) {
  2211.                             // ricostruisco per considerare le date
  2212.                             request = GestoreTokenAttributeAuthorityUtilities.buildDynamicAARequest(configurazionePdDManager,
  2213.                                     protocolFactory, requestInfo,
  2214.                                     policyAttributeAuthority, dynamicParameters, addIdAndDate);
  2215.                         }
  2216.                         else {
  2217.                             request = requestKeyCache;
  2218.                         }
  2219.                        
  2220.                         esitoRecuperoAttributi = GestoreTokenAttributeAuthorityUtilities.readAttributes(log, policyAttributeAuthority,
  2221.                                 protocolFactory,
  2222.                                 dynamicParameters,
  2223.                                 request, portaDelegata,
  2224.                                 pddContext, datiInvocazione.getBusta(),
  2225.                                 datiInvocazione.getIdModulo(), pa, pd,
  2226.                                 datiInvocazione.getState(),
  2227.                                 idDominio, idServizio,
  2228.                                 requestInfo);
  2229.                            
  2230.                         // Aggiungo la risposta in cache (se esiste una cache)  
  2231.                         // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  2232.                         // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  2233.                         // - impostare il noCache a true
  2234.                         if(esitoRecuperoAttributi!=null){ // altrimenti lo mettero' in cache al giro dopo.
  2235.                             esitoRecuperoAttributi.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  2236.                             if(!esitoRecuperoAttributi.isNoCache()){
  2237.                                 GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  2238.                                 try{    
  2239.                                     org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  2240.                                     responseCache.setObject(esitoRecuperoAttributi);
  2241.                                     GestoreToken.cacheAttributeAuthority.put(keyCache,responseCache);
  2242.                                 }catch(UtilsException e){
  2243.                                     GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  2244.                                 }
  2245.                             }
  2246.                         }else{
  2247.                             throw new TokenException(getMessaggioErroreValoreEsitoNull( funzione));
  2248.                         }
  2249.                        
  2250.                         if(esitoRecuperoAttributi.isValido()) {
  2251.                             // ricontrollo tutte le date (l'ho appena preso, dovrebbero essere buone)
  2252.                             GestoreTokenAttributeAuthorityUtilities.validazioneInformazioniAttributiRecuperati(esitoRecuperoAttributi, policyAttributeAuthority,
  2253.                                     policyAttributeAuthority.isSaveErrorInCache(),
  2254.                                     dynamicParameters);
  2255.                         }
  2256.                     }
  2257.                     else {
  2258.                    
  2259.                         // l'ho preso in cache
  2260.                        
  2261.                         if(esitoRecuperoAttributi.isValido()) {
  2262.                             // controllo la data qua
  2263.                             GestoreTokenAttributeAuthorityUtilities.validazioneInformazioniAttributiRecuperati(esitoRecuperoAttributi, policyAttributeAuthority,
  2264.                                     policyAttributeAuthority.isSaveErrorInCache(),
  2265.                                     dynamicParameters);
  2266.                             if(!esitoRecuperoAttributi.isValido() && !esitoRecuperoAttributi.isDateValide()) {
  2267.                                 // DEVO riavviare la negoziazione poichè è scaduto
  2268.                                 GestoreToken.cacheAttributeAuthority.remove(keyCache);
  2269.                                 riavviaNegoziazione = true;
  2270.                             }
  2271.                         }
  2272.                        
  2273.                     }
  2274.                    
  2275.                 } finally{
  2276.                     // fine synchronized
  2277.                     lockAttributeAuthority.release(lock, "readAttributes", idTransazione);
  2278.                 }
  2279.             }
  2280.             else {
  2281.                
  2282.                 // l'ho preso in cache
  2283.                
  2284.                 if(esitoRecuperoAttributi.isValido()) {
  2285.                     // controllo la data qua
  2286.                     GestoreTokenAttributeAuthorityUtilities.validazioneInformazioniAttributiRecuperati(esitoRecuperoAttributi, policyAttributeAuthority,
  2287.                             policyAttributeAuthority.isSaveErrorInCache(),
  2288.                             dynamicParameters);
  2289.                     if(!esitoRecuperoAttributi.isValido() && !esitoRecuperoAttributi.isDateValide()) {
  2290.                         org.openspcoop2.utils.Semaphore lockAttributeAuthority = getLockAttributeAuthority(aaName);
  2291.                         SemaphoreLock lock = lockAttributeAuthority.acquire("removeAttributes", idTransazione);
  2292.                         try {
  2293.                             // DEVO riavviare la negoziazione poichè è scaduto
  2294.                             GestoreToken.cacheAttributeAuthority.remove(keyCache);
  2295.                             riavviaNegoziazione = true;
  2296.                         } finally{
  2297.                             // fine synchronized
  2298.                             lockAttributeAuthority.release(lock, "removeAttributes", idTransazione);
  2299.                         }
  2300.                     }
  2301.                 }
  2302.                
  2303.             }
  2304.         }
  2305.        
  2306.         if(riavviaNegoziazione) {
  2307.             return readAttributes(log, datiInvocazione, pddContext, protocolFactory, portaDelegata,
  2308.                     idDominio, idServizio);
  2309.         }
  2310.         return esitoRecuperoAttributi;
  2311.     }
  2312.    
  2313.     public static InformazioniAttributi normalizeInformazioniAttributi(List<InformazioniAttributi> list, List<AttributeAuthority> aaList) throws Exception {
  2314.        
  2315.         /** int size = list.size();
  2316.         // Fix: deve basarsi sulle AA configurate e non su quelle da cui si e' ottenuto effettivamente una risposta, altrimenti poi le regole cambiano (prefisso AA presente o meno) */
  2317.         int size = aaList.size();
  2318.         if(size==1) {
  2319.             return list.get(0);
  2320.         }
  2321.         else {
  2322.             return new InformazioniAttributi(OpenSPCoop2Properties.getInstance().isGestioneAttributeAuthoritySaveSourceAttributeResponseInfo(), list.toArray(new InformazioniAttributi[1]));
  2323.         }
  2324.     }

  2325.    
  2326.    
  2327.    
  2328.    
  2329.    
  2330.    
  2331.    
  2332.    
  2333.    
  2334.    
  2335.    
  2336.    
  2337.    
  2338.    
  2339.    
  2340.    
  2341.    
  2342.    
  2343.    
  2344.    
  2345.     // ********* [GENERIC-TOKEN] ****************** */
  2346.    
  2347.     public static TokenCacheItem getTokenCacheItem(String keyCache, String funzione, Date now) throws TokenException {
  2348.         TokenCacheItem item = null;
  2349.        
  2350.         if(GestoreToken.cacheGestioneToken!=null){
  2351.            
  2352.             org.openspcoop2.utils.cache.CacheResponse response =
  2353.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  2354.             if(response != null){
  2355.                 if(response.getObject()!=null){
  2356.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  2357.                     item = (TokenCacheItem) response.getObject();
  2358.                     item.setInCache(true);
  2359.                 }else if(response.getException()!=null){
  2360.                     Exception e = (Exception) response.getException();
  2361.                     throw new TokenException("Trovata eccezione '"+response.getException().getClass().getName()+"' in cache non prevista: "+e.getMessage(),e);
  2362.                 }else{
  2363.                     GestoreToken.loggerError(MESSAGE_ELEMENT_CACHE_NE_OGGETTO_NE_ECCEZIONE);
  2364.                 }
  2365.             }
  2366.            
  2367.             if(item!=null) {
  2368.                 item = checkTokenCacheItem(item, keyCache, now, true);
  2369.             }
  2370.         }
  2371.        
  2372.         return item;
  2373.     }
  2374.     private static TokenCacheItem checkTokenCacheItem(TokenCacheItem item, String keyCache, Date now, boolean debug) {
  2375.         boolean tokenExpired = false;
  2376.         if(item.getExp()!=null) {
  2377.             try{
  2378.                 tokenExpired = GestoreTokenValidazioneUtilities.isExpired(now, item.getExp());
  2379.             }catch(Exception e) {
  2380.                 GestoreToken.loggerError("Token presente in cache con chiave '"+keyCache+"', verifica scadenza '"+DateUtils.getSimpleDateFormatMs().format(item.getExp())+"' fallita: "+e.getMessage(),e);
  2381.             }
  2382.         }
  2383.         if(tokenExpired) {
  2384.             if(debug) {
  2385.                 GestoreToken.loggerDebug("Token presente in cache con chiave '"+keyCache+"' risulta scaduto in data '"+DateUtils.getSimpleDateFormatMs().format(item.getExp())+"'");
  2386.             }
  2387.             return null;
  2388.         }
  2389.         return item;
  2390.     }
  2391.    
  2392.     public static void putTokenCacheItem(TokenCacheItem item, String keyCache, String funzione, Date now) {
  2393.        
  2394.         if(GestoreToken.cacheGestioneToken!=null){
  2395.            
  2396.             // Fix: devo prima verificare se ho la chiave in cache prima di mettermi in sincronizzazione.
  2397.             // Qua non va fatto come per gli altri casi, è nell'utilizzo del metodo getTokenCacheItem che lo si fa
  2398.            
  2399.            
  2400.             org.openspcoop2.utils.Semaphore lockNegoziazione = getLockGenericToken(funzione);
  2401.             SemaphoreLock lock = lockNegoziazione.acquireThrowRuntime("putTokenCacheItem", item.getIdTransazione());
  2402.             try {
  2403.                
  2404.                 // per gestire concorrenza
  2405.                 org.openspcoop2.utils.cache.CacheResponse response =
  2406.                     (org.openspcoop2.utils.cache.CacheResponse) GestoreToken.cacheGestioneToken.get(keyCache);
  2407.                 TokenCacheItem itemInCache = null;
  2408.                 if(response != null &&
  2409.                     response.getObject()!=null){
  2410.                     GestoreToken.loggerDebug(GestoreToken.getMessageObjectInCache(response, keyCache, funzione));
  2411.                     itemInCache = (TokenCacheItem) response.getObject();
  2412.                     itemInCache.setInCache(true);
  2413.                 }
  2414.                 if(itemInCache!=null) {
  2415.                     itemInCache = checkTokenCacheItem(itemInCache, keyCache, now, false);
  2416.                 }

  2417.                 if(itemInCache==null) {
  2418.                        
  2419.                     // Aggiungo la risposta in cache (se esiste una cache)  
  2420.                     // Sempre. Se la risposta non deve essere cachata l'implementazione può in alternativa:
  2421.                     // - impostare una eccezione di processamento (che setta automaticamente noCache a true)
  2422.                     // - impostare il noCache a true
  2423.                     item.setInCache(false); // la prima volta che lo recupero sicuramente non era in cache
  2424.                     GestoreToken.loggerInfo(getMessaggioAggiuntaOggettoInCache(keyCache));
  2425.                     try{    
  2426.                         org.openspcoop2.utils.cache.CacheResponse responseCache = new org.openspcoop2.utils.cache.CacheResponse();
  2427.                         responseCache.setObject(item);
  2428.                         GestoreToken.cacheGestioneToken.put(keyCache,responseCache);
  2429.                     }catch(UtilsException e){
  2430.                         GestoreToken.loggerError(getMessaggioErroreInserimentoInCache(keyCache, e));
  2431.                     }
  2432.                    
  2433.                 }
  2434.                
  2435.             }finally {
  2436.                 // fine synchronized
  2437.                 lockNegoziazione.release(lock, "putTokenCacheItem", item.getIdTransazione());
  2438.             }

  2439.         }
  2440.     }
  2441. }