Helper.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.core.config.rs.server.api.impl;

  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Method;
  23. import java.util.AbstractMap.SimpleEntry;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.stream.Collectors;
  29. import java.util.stream.Stream;

  30. import org.apache.commons.beanutils.BeanUtils;
  31. import org.apache.commons.lang.StringUtils;
  32. import org.openspcoop2.core.commons.Filtri;
  33. import org.openspcoop2.core.config.constants.CredenzialeTipo;
  34. import org.openspcoop2.core.config.rs.server.config.ServerProperties;
  35. import org.openspcoop2.core.config.rs.server.model.AuthenticationApiKey;
  36. import org.openspcoop2.core.config.rs.server.model.AuthenticationHttpBasic;
  37. import org.openspcoop2.core.config.rs.server.model.AuthenticationHttps;
  38. import org.openspcoop2.core.config.rs.server.model.AuthenticationHttpsBaseCertificato;
  39. import org.openspcoop2.core.config.rs.server.model.AuthenticationHttpsCertificato;
  40. import org.openspcoop2.core.config.rs.server.model.AuthenticationHttpsConfigurazioneManuale;
  41. import org.openspcoop2.core.config.rs.server.model.AuthenticationPrincipal;
  42. import org.openspcoop2.core.config.rs.server.model.AuthenticationToken;
  43. import org.openspcoop2.core.config.rs.server.model.AuthenticationTokenBase;
  44. import org.openspcoop2.core.config.rs.server.model.ModalitaAccessoEnum;
  45. import org.openspcoop2.core.config.rs.server.model.OneOfBaseCredenzialiCredenziali;
  46. import org.openspcoop2.core.config.rs.server.model.TipoAutenticazioneHttps;
  47. import org.openspcoop2.core.config.rs.server.model.TipoKeystore;
  48. import org.openspcoop2.core.id.IDSoggetto;
  49. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  50. import org.openspcoop2.core.registry.CredenzialiSoggetto;
  51. import org.openspcoop2.core.registry.beans.AccordoServizioParteComuneSintetico;
  52. import org.openspcoop2.core.registry.constants.StatoFunzionalita;
  53. import org.openspcoop2.core.registry.driver.IDAccordoFactory;
  54. import org.openspcoop2.protocol.manifest.constants.ServiceBinding;
  55. import org.openspcoop2.utils.Utilities;
  56. import org.openspcoop2.utils.UtilsException;
  57. import org.openspcoop2.utils.certificate.ArchiveLoader;
  58. import org.openspcoop2.utils.certificate.ArchiveType;
  59. import org.openspcoop2.utils.certificate.CertificateInfo;
  60. import org.openspcoop2.utils.mime.MimeTypes;
  61. import org.openspcoop2.utils.service.beans.Lista;
  62. import org.openspcoop2.utils.service.beans.ProfiloEnum;
  63. import org.openspcoop2.utils.service.context.IContext;
  64. import org.openspcoop2.utils.service.fault.jaxrs.FaultCode;
  65. import org.openspcoop2.utils.transport.http.HttpConstants;
  66. import org.openspcoop2.web.ctrlstat.core.ConsoleSearch;
  67. import org.openspcoop2.web.ctrlstat.servlet.ConsoleHelper;
  68. import org.openspcoop2.web.ctrlstat.servlet.apc.AccordiServizioParteComuneCore;
  69. import org.openspcoop2.web.ctrlstat.servlet.connettori.ConnettoriCostanti;
  70. import org.openspcoop2.web.lib.mvc.BinaryParameter;
  71. import org.openspcoop2.web.lib.mvc.Costanti;
  72. import org.openspcoop2.web.lib.mvc.ServletUtils;

  73. /**
  74.  * Helper
  75.  *
  76.  * @author $Author$
  77.  * @version $Rev$, $Date$
  78.  *
  79.  */
  80. public class Helper extends org.openspcoop2.utils.service.beans.utils.BaseHelper {
  81.    
  82.    
  83.    
  84.     public static <T extends Lista> T returnOrNotFound(T ret ) throws UtilsException {
  85.         boolean throwIfEmpty = ServerProperties.getInstance().isFindall404();
  86.        
  87.         if ( (ret == null || ret.getTotal() <= 0 ) && throwIfEmpty )
  88.             throw FaultCode.NOT_FOUND.toException("Nessun elemento corrisponde ai criteri di ricerca");
  89.        
  90.         return ret;
  91.     }
  92.    
  93.     /**
  94.      * Converte un enum in un altro enum supposto che i valori di enumerazione siano identici.
  95.      * Questo si presta bene a conversioni del tipo HttpMethodEnum -> HttpMethod. In questo caso, pur avendo
  96.      * il primo enum un valore in più - QUALSIASI-, esso viene tradotto a null così come richiesto dalla console.
  97.      *  
  98.      * Potrei utilizzare un terzo parametro per sollevare un eccezione in caso di mancata conversione
  99.      */
  100.     public static final <E1 extends Enum<E1>,E2 extends Enum<E2>> E2 apiEnumToGovway(E1 aenum, Class<E2> toClass  ) {
  101.        
  102.         try {
  103.             return Enum.valueOf(toClass, aenum.name());
  104.         } catch(Exception e) {
  105.             return null;
  106.         }
  107.     //   BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "BASIC"));
  108.     //   return Enum.valueOf( (Class<Enum>)toClass, "BASIC")
  109.     }

  110.     public static final Map<CredenzialeTipo,ModalitaAccessoEnum> modalitaAccessoFromCredenzialeTipo = new HashMap<>();
  111.     static {
  112.         modalitaAccessoFromCredenzialeTipo.put(CredenzialeTipo.BASIC, ModalitaAccessoEnum.HTTP_BASIC);
  113.         modalitaAccessoFromCredenzialeTipo.put(CredenzialeTipo.PRINCIPAL, ModalitaAccessoEnum.PRINCIPAL);
  114.         modalitaAccessoFromCredenzialeTipo.put(CredenzialeTipo.SSL, ModalitaAccessoEnum.HTTPS);
  115.         modalitaAccessoFromCredenzialeTipo.put(CredenzialeTipo.APIKEY, ModalitaAccessoEnum.API_KEY);
  116.         modalitaAccessoFromCredenzialeTipo.put(CredenzialeTipo.TOKEN, ModalitaAccessoEnum.TOKEN);
  117.     }
  118.    
  119.     public static final Map<ModalitaAccessoEnum,CredenzialeTipo> credenzialeTipoFromModalitaAccesso = new HashMap<ModalitaAccessoEnum,CredenzialeTipo>();
  120.     static {
  121.         modalitaAccessoFromCredenzialeTipo.forEach( (cred,mod) -> credenzialeTipoFromModalitaAccesso.put(mod, cred));
  122.     }

  123.    
  124.     public static final Map<ModalitaAccessoEnum,String> tipoAuthFromModalitaAccesso = new HashMap<ModalitaAccessoEnum,String>();
  125.     static {
  126.         tipoAuthFromModalitaAccesso.put(ModalitaAccessoEnum.HTTPS, ConnettoriCostanti.AUTENTICAZIONE_TIPO_SSL);
  127.         tipoAuthFromModalitaAccesso.put(ModalitaAccessoEnum.HTTP_BASIC, ConnettoriCostanti.AUTENTICAZIONE_TIPO_BASIC);
  128.         tipoAuthFromModalitaAccesso.put(ModalitaAccessoEnum.PRINCIPAL, ConnettoriCostanti.AUTENTICAZIONE_TIPO_PRINCIPAL);
  129.         tipoAuthFromModalitaAccesso.put(ModalitaAccessoEnum.API_KEY, ConnettoriCostanti.AUTENTICAZIONE_TIPO_APIKEY);
  130.         tipoAuthFromModalitaAccesso.put(ModalitaAccessoEnum.TOKEN, ConnettoriCostanti.AUTENTICAZIONE_TIPO_TOKEN);
  131.         tipoAuthFromModalitaAccesso.put(null, ConnettoriCostanti.AUTENTICAZIONE_TIPO_NESSUNA);
  132.     }

  133.     public static final Map<String,String> tipoAuthSAFromModalita = Stream.of(
  134.             new SimpleEntry<>("http-basic", ConnettoriCostanti.AUTENTICAZIONE_TIPO_BASIC),
  135.             new SimpleEntry<>("https", ConnettoriCostanti.AUTENTICAZIONE_TIPO_SSL),
  136.             new SimpleEntry<>("principal",ConnettoriCostanti.AUTENTICAZIONE_TIPO_PRINCIPAL),
  137.             new SimpleEntry<>("api-key",ConnettoriCostanti.AUTENTICAZIONE_TIPO_APIKEY),
  138.             new SimpleEntry<>("token",ConnettoriCostanti.AUTENTICAZIONE_TIPO_TOKEN),
  139.             new SimpleEntry<>("custom", ConnettoriCostanti.AUTENTICAZIONE_TIPO_NESSUNA)
  140.         ).collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));


  141.     public static ProfiloEnum getProfiloDefault() throws UtilsException {
  142.         ServerProperties serverProperties = ServerProperties.getInstance();
  143.        
  144.         return profiloFromTipoProtocollo.get(serverProperties.getProtocolloDefault());
  145.     }


  146.     public static String getProtocolloOrDefault(ProfiloEnum profilo) throws UtilsException {
  147.         ServerProperties serverProperties = ServerProperties.getInstance();
  148.         String tipo_protocollo = null;
  149.        
  150.         String modalita = profilo!=null ? profilo.toString() : null;
  151.         if (modalita == null || modalita.length() == 0) {
  152.             tipo_protocollo = serverProperties.getProtocolloDefault();
  153.         }
  154.        
  155.         else {
  156.             tipo_protocollo = tipoProtocolloFromProfilo.get(profilo);
  157.         }
  158.        
  159.         if (tipo_protocollo == null) {
  160.             StringBuilder sb = new StringBuilder("Impossible recuperare il profilo di interoperabilità dalla modalità: ");
  161.             sb.append(modalita);
  162.             throw FaultCode.RICHIESTA_NON_VALIDA.toException(sb.toString());
  163.         }
  164.        
  165.         return tipo_protocollo;
  166.     }


  167.     public static final String getSoggettoOrDefault(String soggetto, ProfiloEnum profilo) throws UtilsException {
  168.        
  169.         if (soggetto == null || soggetto.length() == 0) {
  170.             ServerProperties serverProperties = ServerProperties.getInstance();
  171.             soggetto = serverProperties.getSoggettoDefault(profilo!=null ? profilo.toString() : null);
  172.         }
  173.        
  174.         return soggetto;
  175.     }
  176.    
  177.     public static void overrideAuthParams(HttpRequestWrapper wrap, ConsoleHelper consoleHelper, OneOfBaseCredenzialiCredenziali credenziali,
  178.             ApiKeyInfo apiKeyInfo, boolean updateKey) {
  179.        
  180.         ModalitaAccessoEnum modalitaAccesso = credenziali.getModalitaAccesso();
  181.         if(modalitaAccesso == null) {
  182.             throw FaultCode.RICHIESTA_NON_VALIDA.toException("Modalità di accesso delle credenziali non indicata");
  183.         }
  184.        
  185.         switch(modalitaAccesso) {
  186.         case HTTP_BASIC: {
  187.            
  188.             if(! (credenziali instanceof AuthenticationHttpBasic)) {
  189.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+credenziali.getClass().getName()+"' non compatibili con la modalità '+"+modalitaAccesso.toString()+"+'");
  190.             }
  191.            
  192.             AuthenticationHttpBasic c = (AuthenticationHttpBasic) credenziali;
  193.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_USERNAME, c.getUsername());
  194.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_PASSWORD, c.getPassword());
  195.             if(c.getPassword()!=null && StringUtils.isNotEmpty(c.getPassword())) {
  196.                 wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CHANGE_PASSWORD,
  197.                         Costanti.CHECK_BOX_CONFIG_ENABLE);
  198.             }
  199.            
  200.             break;
  201.         }
  202.         case API_KEY: {
  203.            
  204.             if(! (credenziali instanceof AuthenticationApiKey)) {
  205.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+credenziali.getClass().getName()+"' non compatibili con la modalità '+"+modalitaAccesso.toString()+"+'");
  206.             }
  207.            
  208.             AuthenticationApiKey c = (AuthenticationApiKey) credenziali;
  209.             boolean appId = isAppId(c.isAppId());
  210.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_MULTIPLE_API_KEYS, appId ? Costanti.CHECK_BOX_CONFIG_ENABLE : Costanti.CHECK_BOX_CONFIG_DISABLE);
  211.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_APP_ID, apiKeyInfo.getAppId());
  212.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_API_KEY, apiKeyInfo.getApiKey());
  213.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_PASSWORD, apiKeyInfo.getPassword());
  214.             if(updateKey) {
  215.                 wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CHANGE_PASSWORD,
  216.                         Costanti.CHECK_BOX_CONFIG_ENABLE);
  217.             }
  218.            
  219.             break;
  220.         }
  221.         case HTTPS: {
  222.            
  223.             if(! (credenziali instanceof AuthenticationHttps)) {
  224.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+credenziali.getClass().getName()+"' non compatibili con la modalità '+"+modalitaAccesso.toString()+"+'");
  225.             }
  226.                        
  227.             AuthenticationHttps c = (AuthenticationHttps) credenziali;
  228.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_WIZARD_STEP,
  229.                     ConnettoriCostanti.VALUE_PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_NO_WIZARD);
  230.            
  231.             switch (c.getCertificato().getTipo()) {
  232.             case CERTIFICATO:
  233.                
  234.                 if(c.getCertificato() instanceof AuthenticationHttpsCertificato) {
  235.                
  236.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL,
  237.                             ConnettoriCostanti.VALUE_PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_UPLOAD_CERTIFICATO);
  238.                     AuthenticationHttpsCertificato certificate = (AuthenticationHttpsCertificato) c.getCertificato();
  239.                     consoleHelper.registerBinaryParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_FILE_CERTIFICATO, certificate.getArchivio());
  240.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_TIPO_ARCHIVIO, certificate.getTipoCertificato().toString());
  241.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_ALIAS_CERTIFICATO, certificate.getAlias());
  242.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_FILE_CERTIFICATO_PASSWORD, certificate.getPassword());
  243.                    
  244.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_VERIFICA_TUTTI_CAMPI,
  245.                             certificate.isStrictVerification()? Costanti.CHECK_BOX_ENABLED : Costanti.CHECK_BOX_CONFIG_DISABLE);
  246.                    
  247.                 }
  248.                 else {
  249.                     throw FaultCode.RICHIESTA_NON_VALIDA.toException("Certificato fornito '"+c.getCertificato().getClass().getName()+"' non compatibile con il tipo '"+c.getCertificato().getTipo()+"' ");
  250.                 }
  251.                
  252.                 break;
  253.             case CONFIGURAZIONE_MANUALE:
  254.                
  255.                 if(c.getCertificato() instanceof AuthenticationHttpsConfigurazioneManuale) {
  256.                    
  257.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL,
  258.                             ConnettoriCostanti.VALUE_PARAMETRO_CREDENZIALI_AUTENTICAZIONE_CONFIGURAZIONE_SSL_CONFIGURAZIONE_MANUALE);
  259.                     AuthenticationHttpsConfigurazioneManuale creManuale = (AuthenticationHttpsConfigurazioneManuale) c.getCertificato();
  260.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_SUBJECT, creManuale.getSubject());
  261.                     wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_ISSUER, creManuale.getIssuer());
  262.                    
  263.                 }
  264.                 else {
  265.                     throw FaultCode.RICHIESTA_NON_VALIDA.toException("Certificato fornito '"+c.getCertificato().getClass().getName()+"' non compatibile con il tipo '"+c.getCertificato().getTipo()+"' ");
  266.                 }
  267.                
  268.                 break;
  269.             }
  270.            
  271.             // Token per Modi insieme al certificato
  272.             if(c.getToken()!=null) {
  273.                 wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_TOKEN_CLIENT_ID, c.getToken().getIdentificativo());
  274.                 wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_TOKEN_POLICY,c.getToken().getTokenPolicy());
  275.             }
  276.            
  277.             break;
  278.         }
  279.         case PRINCIPAL: {
  280.            
  281.             if(! (credenziali instanceof AuthenticationPrincipal)) {
  282.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+credenziali.getClass().getName()+"' non compatibili con la modalità '+"+modalitaAccesso.toString()+"+'");
  283.             }
  284.            
  285.             AuthenticationPrincipal c = (AuthenticationPrincipal) credenziali;
  286.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_PRINCIPAL, c.getUserid());
  287.             break;
  288.         }
  289.         case TOKEN: {
  290.            
  291.             if(! (credenziali instanceof AuthenticationToken)) {
  292.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+credenziali.getClass().getName()+"' non compatibili con la modalità '+"+modalitaAccesso.toString()+"+'");
  293.             }
  294.            
  295.             AuthenticationToken c = (AuthenticationToken) credenziali;
  296.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_TOKEN_CLIENT_ID, c.getIdentificativo());
  297.             wrap.overrideParameter(ConnettoriCostanti.PARAMETRO_CREDENZIALI_AUTENTICAZIONE_TOKEN_POLICY,c.getTokenPolicy());
  298.             break;
  299.         }
  300.         }
  301.     }
  302.    
  303.    
  304.     /**
  305.      * Swagger passa le credenziali come una linkedHashMap.
  306.      * Dobbiamo trasformarla nei relativi oggetti di autenticazione.
  307.      *
  308.      * @param applicativo
  309.      * @return
  310.      * @throws Exception
  311.      */
  312.     public static OneOfBaseCredenzialiCredenziali translateCredenziali(OneOfBaseCredenzialiCredenziali creds, boolean create) {
  313.        
  314.         if(creds==null || creds.getModalitaAccesso()==null) {
  315.             return null;
  316.         }
  317.        
  318.         OneOfBaseCredenzialiCredenziali ret = null;
  319.         ModalitaAccessoEnum tipoAuth = creds.getModalitaAccesso();
  320.    
  321.         switch (tipoAuth) {
  322.         case HTTP_BASIC: {
  323.             ret = (AuthenticationHttpBasic) creds;
  324.             if(create) {
  325.                 AuthenticationHttpBasic basic = (AuthenticationHttpBasic) ret;
  326.                 if(basic.getPassword()==null || StringUtils.isEmpty(basic.getPassword())) {
  327.                     throw FaultCode.RICHIESTA_NON_VALIDA.toException("Nell'operazione richiesta è obbligatorio indicare la password per il tipo di autenticazione '"+tipoAuth+"'");
  328.                 }
  329.             }
  330.             break;
  331.         }
  332.         case HTTPS: {
  333.             ret = (AuthenticationHttps) creds;
  334.             break;
  335.         }
  336.         case PRINCIPAL: {
  337.             ret = (AuthenticationPrincipal) creds;
  338.             break;
  339.         }
  340.         case API_KEY: {
  341.             ret = (AuthenticationApiKey) creds;
  342.             break;
  343.         }
  344.         case TOKEN: {
  345.             ret = (AuthenticationToken) creds;
  346.             break;
  347.         }
  348.         default:
  349.             ret = null;
  350.             break;
  351.            
  352.         }
  353.         return ret;
  354.     }
  355.    
  356.     /**
  357.      * Trasforma un oggetto di tipo credenziali parte API (è assunto ben formato) nei numerosi oggetti Credenziale* generati
  358.      * automaticamente all'interno del progetto e identici.
  359.      *
  360.      * @param creds
  361.      * @param tipoAuth
  362.      * @param credClass La classe verso cui tradurre
  363.      * @param enumClass La modalità di accesso, ovvero il campo "tipo" della classe verso cui tradurre.
  364.      * @throws UtilsException
  365.      */
  366.    
  367.     // TODO: Manage exceptions.
  368.     @SuppressWarnings({ "unchecked", "rawtypes" })
  369.     public static <T,E> List<T> apiCredenzialiToGovwayCred(Object creds, ModalitaAccessoEnum tipoAuth, Class<T> credClass, Class<E> enumClass, ApiKeyInfo keyInfo)
  370.             throws IllegalAccessException, InvocationTargetException, InstantiationException, UtilsException {
  371.        
  372.         if (!enumClass.isEnum())
  373.             throw new IllegalArgumentException("Il parametro enumClass deve essere un'enumerazione");
  374.        
  375.         List<T> lstRet = new ArrayList<T>();
  376.        
  377.         T ret = Utilities.newInstance(credClass);
  378.        
  379.         switch (tipoAuth) {
  380.         case HTTP_BASIC: {
  381.            
  382.             if(! (creds instanceof AuthenticationHttpBasic)) {
  383.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+creds.getClass().getName()+"' non compatibili con la modalità '+"+tipoAuth.toString()+"+'");
  384.             }
  385.            
  386.             AuthenticationHttpBasic auth = (AuthenticationHttpBasic) creds;
  387.             BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "BASIC"));
  388.             BeanUtils.setProperty(ret, "user", auth.getUsername());
  389.             BeanUtils.setProperty(ret, "password", auth.getPassword());
  390.             lstRet.add(ret);
  391.             break;
  392.         }
  393.         case HTTPS: {
  394.            
  395.             if(! (creds instanceof AuthenticationHttps)) {
  396.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+creds.getClass().getName()+"' non compatibili con la modalità '+"+tipoAuth.toString()+"+'");
  397.             }
  398.            
  399.             AuthenticationHttps auth = (AuthenticationHttps) creds;
  400.             BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "SSL"));
  401.             switch (auth.getCertificato().getTipo()) {
  402.             case CERTIFICATO:
  403.                 AuthenticationHttpsCertificato cre = (AuthenticationHttpsCertificato) auth.getCertificato();
  404.                 ArchiveType type = ArchiveType.CER;
  405.                 String alias = cre.getAlias();
  406.                 String password = cre.getPassword();
  407.                 if(cre.getTipoCertificato()!=null) {
  408.                     type = ArchiveType.valueOf(cre.getTipoCertificato().toString());
  409.                 }
  410.                 CertificateInfo cInfo = ArchiveLoader.load(type, cre.getArchivio(), alias, password).getCertificate();
  411.                 BeanUtils.setProperty(ret, "certificate", cre.getArchivio());
  412.                 BeanUtils.setProperty(ret, "certificateStrictVerification", cre.isStrictVerification());
  413.                 BeanUtils.setProperty(ret, "cnSubject", cInfo.getSubject().getCN());
  414.                 BeanUtils.setProperty(ret, "cnIssuer", cInfo.getIssuer().getCN());  
  415.                 lstRet.add(ret);
  416.                
  417.                 // lettura altri certificati
  418.                 List<AuthenticationHttpsBaseCertificato> certificati = auth.getCertificati();
  419.                 if(certificati!= null && certificati.size() > 0) {
  420.                     for (AuthenticationHttpsBaseCertificato secondaryCre : certificati) {
  421.                         T cert = Utilities.newInstance(credClass);
  422.                         BeanUtils.setProperty(cert, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "SSL"));
  423.                        
  424.                         ArchiveType secondaryType = ArchiveType.CER;
  425.                         String secondaryAlias = secondaryCre.getAlias();
  426.                         String secondaryPassword = secondaryCre.getPassword();
  427.                         if(secondaryCre.getTipoCertificato()!=null) {
  428.                             secondaryType = ArchiveType.valueOf(secondaryCre.getTipoCertificato().toString());
  429.                         }
  430.                         CertificateInfo secondaryCInfo = ArchiveLoader.load(secondaryType, secondaryCre.getArchivio(), secondaryAlias, secondaryPassword).getCertificate();
  431.                         BeanUtils.setProperty(cert, "certificate", secondaryCre.getArchivio());
  432.                         BeanUtils.setProperty(cert, "certificateStrictVerification", secondaryCre.isStrictVerification());
  433.                         BeanUtils.setProperty(cert, "cnSubject", secondaryCInfo.getSubject().getCN());
  434.                         BeanUtils.setProperty(cert, "cnIssuer", secondaryCInfo.getIssuer().getCN());    
  435.                        
  436.                         lstRet.add(cert);
  437.                     }
  438.                 }
  439.                
  440.                 break;
  441.             case CONFIGURAZIONE_MANUALE:
  442.                 AuthenticationHttpsConfigurazioneManuale creManuale = (AuthenticationHttpsConfigurazioneManuale) auth.getCertificato();
  443.                 BeanUtils.setProperty(ret, "subject", creManuale.getSubject());
  444.                 BeanUtils.setProperty(ret, "issuer", creManuale.getIssuer());
  445.                 lstRet.add(ret);
  446.                 break;
  447.             }
  448.            
  449.             // Token per Modi insieme al certificato
  450.             if(auth.getToken()!=null) {
  451.                 BeanUtils.setProperty(ret, "user", auth.getToken().getIdentificativo());
  452.                 BeanUtils.setProperty(ret, "tokenPolicy", auth.getToken().getTokenPolicy());
  453.             }
  454.            
  455.             break;
  456.         }
  457.         case PRINCIPAL: {
  458.            
  459.             if(! (creds instanceof AuthenticationPrincipal)) {
  460.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+creds.getClass().getName()+"' non compatibili con la modalità '+"+tipoAuth.toString()+"+'");
  461.             }
  462.            
  463.             AuthenticationPrincipal auth = (AuthenticationPrincipal) creds;
  464.             BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "PRINCIPAL"));
  465.             BeanUtils.setProperty(ret, "user", auth.getUserid());
  466.             lstRet.add(ret);
  467.             break;
  468.         }
  469.         case API_KEY: {
  470.            
  471.             if(! (creds instanceof AuthenticationApiKey)) {
  472.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+creds.getClass().getName()+"' non compatibili con la modalità '+"+tipoAuth.toString()+"+'");
  473.             }
  474.             if(keyInfo==null) {
  475.                 throw new UtilsException("KeyInfo unavailable");
  476.             }
  477.            
  478.             AuthenticationApiKey auth = (AuthenticationApiKey) creds;
  479.             BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "APIKEY"));
  480.             BeanUtils.setProperty(ret, "user", keyInfo.getAppId());
  481.             BeanUtils.setProperty(ret, "password", keyInfo.getPassword());
  482.             boolean appId = isAppId(auth.isAppId());
  483.             BeanUtils.setProperty(ret, "appId", appId);
  484.             BeanUtils.setProperty(ret, "certificateStrictVerification", keyInfo.isCifrata());
  485.             lstRet.add(ret);
  486.             break;
  487.         }
  488.        
  489.         case TOKEN: {
  490.            
  491.             if(! (creds instanceof AuthenticationToken)) {
  492.                 throw FaultCode.RICHIESTA_NON_VALIDA.toException("Credenziali '"+creds.getClass().getName()+"' non compatibili con la modalità '+"+tipoAuth.toString()+"+'");
  493.             }
  494.        
  495.             AuthenticationToken auth = (AuthenticationToken) creds;
  496.             BeanUtils.setProperty(ret, "tipo", Enum.valueOf( (Class<Enum>)enumClass, "TOKEN"));
  497.             BeanUtils.setProperty(ret, "user", auth.getIdentificativo());
  498.             BeanUtils.setProperty(ret, "tokenPolicy", auth.getTokenPolicy());
  499.             lstRet.add(ret);
  500.             break;
  501.         }
  502.        
  503.         default:
  504.             BeanUtils.setProperty(ret, "tipo", null);
  505.             lstRet.add(ret);
  506.             break;
  507.         }
  508.        
  509.         return lstRet;
  510.     }

  511.    
  512.     public static final <T,E> OneOfBaseCredenzialiCredenziali govwayCredenzialiToApi(List<?> govwayCredsList, Class<T> credClass, Class<E> enumClass) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
  513.        
  514.         if (!enumClass.isEnum())
  515.             throw new IllegalArgumentException("Il parametro enumClass deve essere un'enumerazione");
  516.        
  517.         OneOfBaseCredenzialiCredenziali ret = null;    
  518.        
  519.         // Questo è il caso di autenticazione di tipo NESSUNO.
  520.         if (govwayCredsList == null)
  521.             return ret;
  522.        
  523.         Object govwayCreds = govwayCredsList.get(0); // riportato dal metodo chiamante
  524.        
  525.         String tipo = BeanUtils.getProperty(govwayCreds, "tipo");
  526.        
  527.         if ("basic".equals(tipo)) {
  528.             AuthenticationHttpBasic auth = new AuthenticationHttpBasic();
  529.             auth.setUsername(BeanUtils.getProperty(govwayCreds, "user"));
  530.            
  531.             Method mCertificateStrictVerification = credClass.getMethod("isCertificateStrictVerification");
  532.             boolean cifrata = (Boolean) mCertificateStrictVerification.invoke(govwayCreds);
  533.             if(!cifrata) {
  534.                 auth.setPassword(BeanUtils.getProperty(govwayCreds, "password"));
  535.             }
  536.             auth.setModalitaAccesso(ModalitaAccessoEnum.HTTP_BASIC);
  537.             ret = auth;
  538.         }
  539.         else if ("ssl".equals(tipo)) {
  540.             AuthenticationHttps auth = new AuthenticationHttps();
  541.             Method mCertificate = credClass.getMethod("getCertificate");
  542.             Object oCertificate = mCertificate.invoke(govwayCreds);
  543.             if(oCertificate==null) {
  544.                 AuthenticationHttpsConfigurazioneManuale manuale = new AuthenticationHttpsConfigurazioneManuale();
  545.                 manuale.setTipo(TipoAutenticazioneHttps.CONFIGURAZIONE_MANUALE);
  546.                 manuale.setSubject(BeanUtils.getProperty(govwayCreds, "subject"));  
  547.                 manuale.setIssuer(BeanUtils.getProperty(govwayCreds, "issuer"));    
  548.                 auth.setCertificato(manuale);
  549.             }
  550.             else {
  551.                 AuthenticationHttpsCertificato certificato = new AuthenticationHttpsCertificato();
  552.                 certificato.setTipo(TipoAutenticazioneHttps.CERTIFICATO);
  553.                 certificato.setTipoCertificato(TipoKeystore.CER);
  554.                 certificato.setArchivio((byte[])oCertificate);
  555.                 Method mCertificateStrictVerification = credClass.getMethod("isCertificateStrictVerification");
  556.                 certificato.setStrictVerification((Boolean) mCertificateStrictVerification.invoke(govwayCreds));
  557.                 auth.setCertificato(certificato);
  558.             }
  559.             auth.setModalitaAccesso(ModalitaAccessoEnum.HTTPS);
  560.            
  561.             if(govwayCredsList.size() > 1) { // riporto i certificati aggiuntivi
  562.                 List<AuthenticationHttpsBaseCertificato> certificati = new ArrayList<AuthenticationHttpsBaseCertificato>();
  563.                 for (int i = 1; i < govwayCredsList.size(); i++) {
  564.                     Object govwayCredsCertificato = govwayCredsList.get(i);
  565.                     AuthenticationHttpsBaseCertificato certificato = new AuthenticationHttpsBaseCertificato();
  566.                     certificato.setTipoCertificato(TipoKeystore.CER);
  567.                     Object oCertificateCertificato = mCertificate.invoke(govwayCredsCertificato);
  568.                     certificato.setArchivio((byte[])oCertificateCertificato);
  569.                     Method mCertificateStrictVerification = credClass.getMethod("isCertificateStrictVerification");
  570.                     certificato.setStrictVerification((Boolean) mCertificateStrictVerification.invoke(govwayCredsCertificato));
  571.                    
  572.                     certificati.add(certificato );
  573.                 }
  574.                 auth.setCertificati(certificati );
  575.             }  
  576.            
  577.             // Token per Modi insieme al certificato
  578.             String credenzialiSoggettoClassName = CredenzialiSoggetto.class.getName()+"";
  579.             if(!credenzialiSoggettoClassName.equals(credClass.getName())) {
  580.                 String identificativo = BeanUtils.getProperty(govwayCreds, "user");
  581.                 String tokenPolicy = BeanUtils.getProperty(govwayCreds, "tokenPolicy");
  582.                 if(tokenPolicy!=null && identificativo!=null) {
  583.                     AuthenticationTokenBase modiToken = new AuthenticationTokenBase();
  584.                     modiToken.setIdentificativo(identificativo);
  585.                     modiToken.setTokenPolicy(tokenPolicy);
  586.                     auth.setToken(modiToken);
  587.                 }
  588.             }
  589.        
  590.             ret = auth;
  591.         }
  592.         else if ("principal".equals(tipo)) {
  593.             AuthenticationPrincipal auth = new AuthenticationPrincipal();
  594.             auth.setUserid(BeanUtils.getProperty(govwayCreds, "user"));
  595.             auth.setModalitaAccesso(ModalitaAccessoEnum.PRINCIPAL);
  596.             ret = auth;
  597.         }
  598.         else if ("apikey".equals(tipo)) {
  599.             AuthenticationApiKey auth = new AuthenticationApiKey();
  600.             Method mAppId = credClass.getMethod("isAppId");
  601.             boolean appId = (Boolean) mAppId.invoke(govwayCreds);
  602.             auth.setAppId(appId);
  603.             auth.setModalitaAccesso(ModalitaAccessoEnum.API_KEY);
  604.             ret = auth;
  605.         }
  606.         else if ("token".equals(tipo)) {
  607.             AuthenticationToken auth = new AuthenticationToken();
  608.             auth.setIdentificativo(BeanUtils.getProperty(govwayCreds, "user"));
  609.             auth.setTokenPolicy(BeanUtils.getProperty(govwayCreds, "tokenPolicy"));
  610.             auth.setModalitaAccesso(ModalitaAccessoEnum.TOKEN);
  611.             ret = auth;
  612.         }
  613.        
  614.         return ret;
  615.     }
  616.    
  617.    
  618.     public static final ModalitaAccessoEnum credenzialiToModalita(Object obj) {
  619.         if (obj == null) return null;
  620.        
  621.         if (obj instanceof AuthenticationHttpBasic)
  622.             return ModalitaAccessoEnum.HTTP_BASIC;
  623.        
  624.         if (obj instanceof AuthenticationHttps)
  625.             return ModalitaAccessoEnum.HTTPS;
  626.        
  627.         if (obj instanceof AuthenticationPrincipal)
  628.             return ModalitaAccessoEnum.PRINCIPAL;
  629.         else
  630.             throw new IllegalArgumentException("credenzialiToModalita(): Tipo argomento sconosciuto");
  631.     }
  632.    
  633.    


  634.     public static final ConsoleSearch setupRicercaPaginata(String q, Integer limit, Integer offset, int idLista) {
  635.         ConsoleSearch ricerca = new ConsoleSearch();
  636.        
  637.         if (limit != null && limit != 0)
  638.             ricerca.setPageSize(idLista, limit);
  639.         if (offset != null)
  640.             ricerca.setIndexIniziale(idLista, offset);
  641.         if (q == null) q = "";
  642.        
  643.         q = q.trim();
  644.         if (q.equals("")) {
  645.             ricerca.setSearchString(idLista, org.openspcoop2.core.constants.Costanti.SESSION_ATTRIBUTE_VALUE_RICERCA_UNDEFINED);
  646.         } else {
  647.             ricerca.setSearchString(idLista, q);
  648.         }
  649.         return ricerca;
  650.     }
  651.    
  652.     public static final ConsoleSearch setupRicercaPaginata(String q, Integer limit, Integer offset, int idLista, IDSoggetto idSoggetto, String tipo_protocollo) {
  653.         ConsoleSearch ricerca = setupRicercaPaginata( q, limit, offset, idLista );
  654.        
  655.         ricerca.addFilter(idLista, Filtri.FILTRO_SOGGETTO, idSoggetto.toString());
  656.         ricerca.addFilter(idLista, Filtri.FILTRO_PROTOCOLLO, tipo_protocollo );
  657.         return ricerca;
  658.     }
  659.    
  660.    
  661.     public static final boolean statoFunzionalitaToBool(StatoFunzionalita sf) {
  662.         if (sf == null) return false;
  663.        
  664.         switch (sf) {
  665.         case ABILITATO: return true;
  666.         case DISABILITATO: return false;
  667.         default: return false;
  668.         }
  669.     }
  670.    
  671.     public static final boolean statoFunzionalitaConfToBool(org.openspcoop2.core.config.constants.StatoFunzionalita sf) {
  672.         if (sf == null) return false;
  673.        
  674.         switch (sf) {
  675.         case ABILITATO: return true;
  676.         case DISABILITATO: return false;
  677.         default: return false;
  678.         }
  679.     }

  680.    
  681.     @Deprecated
  682.     public static final String boolToYesNo(boolean v) {
  683.         return ServletUtils.boolToCheckBoxStatus(v);
  684.     }
  685.    
  686.     public static final StatoFunzionalita boolToStatoFunzionalita(Boolean v) {
  687.         return v ? StatoFunzionalita.ABILITATO : StatoFunzionalita.DISABILITATO;
  688.     }
  689.    
  690.     public static final org.openspcoop2.core.config.constants.StatoFunzionalita boolToStatoFunzionalitaConf(Boolean v) {
  691.         if (v == null) v = false;
  692.        
  693.         return v ? org.openspcoop2.core.config.constants.StatoFunzionalita.ABILITATO : org.openspcoop2.core.config.constants.StatoFunzionalita.DISABILITATO;
  694.     }


  695.     public static final BinaryParameter toBinaryParameter(byte[] value) {
  696.         BinaryParameter ret = new BinaryParameter();
  697.         ret.setValue(value);
  698.         return ret;
  699.     }
  700.    
  701.     public static final AccordoServizioParteComune getAccordoFull(String nome, int versione, IDSoggetto idSoggReferente,    AccordiServizioParteComuneCore apcCore)  {
  702.         return evalnull( () -> apcCore.getAccordoServizioFull(IDAccordoFactory.getInstance().getIDAccordoFromValues(nome, idSoggReferente, versione)));
  703.     }
  704.    
  705.     public static final AccordoServizioParteComuneSintetico getAccordoSintetico(String nome, int versione, IDSoggetto idSoggReferente,  AccordiServizioParteComuneCore apcCore)  {
  706.         return evalnull( () -> apcCore.getAccordoServizioSintetico(IDAccordoFactory.getInstance().getIDAccordoFromValues(nome, idSoggReferente, versione)));
  707.     }

  708.     public static final ServiceBinding toManifestServiceBinding(
  709.             org.openspcoop2.core.registry.constants.ServiceBinding serviceBinding) {

  710.         switch(serviceBinding) {
  711.         case REST:
  712.             return ServiceBinding.REST;
  713.         case SOAP:
  714.             return ServiceBinding.SOAP;
  715.         default:
  716.             return null;
  717.         }
  718.            
  719.     }
  720.    
  721.     public static void setContentType(IContext context, String fileName) throws UtilsException {
  722.         String mimeType = null;
  723.         if(fileName.contains(".")){
  724.             String ext = null;
  725.             try{
  726.                 ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
  727.             }catch(Exception e){
  728.                 // ignore
  729.             }
  730.             MimeTypes mimeTypes = MimeTypes.getInstance();
  731.             if(ext!=null && mimeTypes.existsExtension(ext)){
  732.                 mimeType = mimeTypes.getMimeType(ext);
  733.                 //System.out.println("CUSTOM ["+mimeType+"]");      
  734.             }
  735.             else{
  736.                 mimeType = HttpConstants.CONTENT_TYPE_X_DOWNLOAD;
  737.             }
  738.         }
  739.         else{
  740.             mimeType = HttpConstants.CONTENT_TYPE_X_DOWNLOAD;
  741.         }
  742.        
  743.         context.getServletResponse().setContentType(mimeType);
  744.     }

  745.     public static boolean isAppId(Boolean appIdObject) {
  746.         boolean appId = false;
  747.         if(appIdObject!=null) {
  748.             appId = appIdObject;
  749.         }
  750.         return appId;
  751.     }
  752. }