ServicesUtils.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.services;

  21. import java.io.ByteArrayOutputStream;
  22. import java.security.SecureRandom;
  23. import java.util.Enumeration;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Objects;
  27. import java.util.Properties;

  28. import javax.servlet.http.HttpServletRequest;
  29. import javax.wsdl.Binding;
  30. import javax.wsdl.Port;
  31. import javax.wsdl.PortType;
  32. import javax.xml.soap.SOAPEnvelope;
  33. import javax.xml.soap.SOAPHeader;

  34. import org.apache.commons.io.output.NullOutputStream;
  35. import org.openspcoop2.core.config.CorsConfigurazione;
  36. import org.openspcoop2.core.config.PortaApplicativa;
  37. import org.openspcoop2.core.config.PortaDelegata;
  38. import org.openspcoop2.core.config.constants.RuoloContesto;
  39. import org.openspcoop2.core.config.constants.StatoFunzionalita;
  40. import org.openspcoop2.core.config.constants.TipoGestioneCORS;
  41. import org.openspcoop2.core.config.driver.db.DriverConfigurazioneDB;
  42. import org.openspcoop2.core.constants.Costanti;
  43. import org.openspcoop2.core.constants.TipoPdD;
  44. import org.openspcoop2.core.constants.TransferLengthModes;
  45. import org.openspcoop2.core.id.IDAccordo;
  46. import org.openspcoop2.core.id.IDPortaApplicativa;
  47. import org.openspcoop2.core.id.IDPortaDelegata;
  48. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  49. import org.openspcoop2.core.registry.AccordoServizioParteSpecifica;
  50. import org.openspcoop2.core.registry.constants.TipologiaServizio;
  51. import org.openspcoop2.core.registry.driver.IDAccordoFactory;
  52. import org.openspcoop2.core.registry.driver.db.DriverRegistroServiziDB;
  53. import org.openspcoop2.core.registry.wsdl.AccordoServizioWrapper;
  54. import org.openspcoop2.core.registry.wsdl.AccordoServizioWrapperUtilities;
  55. import org.openspcoop2.generic_project.dao.jdbc.JDBCServiceManagerBase;
  56. import org.openspcoop2.message.OpenSPCoop2Message;
  57. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  58. import org.openspcoop2.message.OpenSPCoop2MessageProperties;
  59. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  60. import org.openspcoop2.message.constants.MessageType;
  61. import org.openspcoop2.message.constants.ServiceBinding;
  62. import org.openspcoop2.message.exception.MessageException;
  63. import org.openspcoop2.message.exception.MessageNotSupportedException;
  64. import org.openspcoop2.message.exception.ParseExceptionUtils;
  65. import org.openspcoop2.message.soap.SoapUtils;
  66. import org.openspcoop2.message.soap.reader.OpenSPCoop2MessageSoapStreamReader;
  67. import org.openspcoop2.message.xml.MessageXMLUtils;
  68. import org.openspcoop2.monitor.sdk.transaction.FaseTracciamento;
  69. import org.openspcoop2.pdd.config.CachedConfigIntegrationReader;
  70. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  71. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  72. import org.openspcoop2.pdd.config.UrlInvocazioneAPI;
  73. import org.openspcoop2.pdd.core.CORSFilter;
  74. import org.openspcoop2.pdd.core.CORSWrappedHttpServletResponse;
  75. import org.openspcoop2.pdd.core.CostantiPdD;
  76. import org.openspcoop2.pdd.core.PdDContext;
  77. import org.openspcoop2.pdd.core.controllo_traffico.CostantiControlloTraffico;
  78. import org.openspcoop2.pdd.core.handlers.HandlerException;
  79. import org.openspcoop2.pdd.core.integrazione.HeaderIntegrazione;
  80. import org.openspcoop2.pdd.core.integrazione.UtilitiesIntegrazione;
  81. import org.openspcoop2.pdd.core.integrazione.peer.HeaderMap;
  82. import org.openspcoop2.pdd.logger.MsgDiagnosticiProperties;
  83. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  84. import org.openspcoop2.pdd.services.connector.ConnectorException;
  85. import org.openspcoop2.pdd.services.connector.ConnectorUtils;
  86. import org.openspcoop2.pdd.services.connector.messages.ConnectorInMessage;
  87. import org.openspcoop2.pdd.services.connector.messages.ConnectorOutMessage;
  88. import org.openspcoop2.protocol.basic.BasicComponentFactory;
  89. import org.openspcoop2.protocol.basic.registry.ServiceIdentificationReader;
  90. import org.openspcoop2.protocol.registry.CachedRegistryReader;
  91. import org.openspcoop2.protocol.registry.RegistroServiziManager;
  92. import org.openspcoop2.protocol.sdk.Context;
  93. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  94. import org.openspcoop2.protocol.sdk.ProtocolException;
  95. import org.openspcoop2.protocol.sdk.builder.EsitoTransazione;
  96. import org.openspcoop2.protocol.sdk.builder.InformazioniErroriInfrastrutturali;
  97. import org.openspcoop2.protocol.sdk.config.IProtocolManager;
  98. import org.openspcoop2.protocol.sdk.constants.EsitoTransazioneName;
  99. import org.openspcoop2.protocol.sdk.constants.IDService;
  100. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  101. import org.openspcoop2.protocol.sdk.registry.IConfigIntegrationReader;
  102. import org.openspcoop2.protocol.sdk.registry.IRegistryReader;
  103. import org.openspcoop2.protocol.sdk.registry.RegistryNotFound;
  104. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  105. import org.openspcoop2.protocol.sdk.state.URLProtocolContext;
  106. import org.openspcoop2.protocol.utils.EsitiProperties;
  107. import org.openspcoop2.protocol.utils.IDSerialGenerator;
  108. import org.openspcoop2.utils.LimitExceededIOException;
  109. import org.openspcoop2.utils.NameValue;
  110. import org.openspcoop2.utils.TimeoutIOException;
  111. import org.openspcoop2.utils.Utilities;
  112. import org.openspcoop2.utils.UtilsException;
  113. import org.openspcoop2.utils.UtilsRuntimeException;
  114. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  115. import org.openspcoop2.utils.transport.TransportUtils;
  116. import org.openspcoop2.utils.transport.http.CORSRequestType;
  117. import org.openspcoop2.utils.transport.http.ContentTypeUtilities;
  118. import org.openspcoop2.utils.transport.http.HttpConstants;
  119. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  120. import org.openspcoop2.utils.transport.http.HttpUtilities;
  121. import org.openspcoop2.utils.transport.http.WrappedHttpServletResponse;
  122. import org.openspcoop2.utils.wsdl.DefinitionWrapper;
  123. import org.openspcoop2.utils.wsdl.WSDLUtilities;
  124. import org.slf4j.Logger;


  125. /**
  126.  * Libreria utilizzata dalle servlet contenente metodi che implementano
  127.  * le funzioni precedentemente implementate negli Handler.
  128.  *
  129.  *
  130.  * @author Nardi Lorenzo (nardi@link.it)
  131.  * @author Tommaso Burlon (tommaso.burlon@link.it)
  132.  * @author $Author$
  133.  * @version $Rev$, $Date$
  134.  */
  135. public class ServicesUtils {
  136.    
  137.     private ServicesUtils() {}

  138.     private static java.util.Random internalRnd = null;
  139.     private static synchronized void initRandom() {
  140.         if(internalRnd==null) {
  141.             internalRnd = new SecureRandom();
  142.         }
  143.     }
  144.     public static java.util.Random getRandom() {
  145.         if(internalRnd==null) {
  146.             initRandom();
  147.         }
  148.         return internalRnd;
  149.     }
  150.    
  151.    
  152.     public static ServiceIdentificationReader getServiceIdentificationReader(Logger logCore, RequestInfo requestInfo,
  153.             RegistroServiziManager registroServiziManager, ConfigurazionePdDManager configurazionePdDManager) throws Exception{
  154.         if(requestInfo==null) {
  155.             throw new Exception("Param requestInfo is null");
  156.         }
  157.         IRegistryReader registryReader = new CachedRegistryReader(logCore, requestInfo.getProtocolFactory(), registroServiziManager, requestInfo);
  158.         IConfigIntegrationReader configIntegrationReader = new CachedConfigIntegrationReader(logCore, requestInfo.getProtocolFactory(), configurazionePdDManager, requestInfo);
  159.         return new ServiceIdentificationReader(registryReader, configIntegrationReader, requestInfo.getProtocolFactory(), logCore);
  160.     }
  161.    
  162.    
  163.     public static boolean isConnessioneClientNonDisponibile(Throwable t){
  164.         if(t instanceof java.net.SocketException){
  165.             return true;
  166.         }
  167.         else if(Utilities.existsInnerException(t, java.net.SocketException.class)){
  168.             return true;
  169.         }
  170.         else if(Utilities.existsInnerException(t, java.io.IOException.class)){
  171.             Throwable tInner = Utilities.getInnerException(t, java.io.IOException.class);
  172.             if(tInner!=null && tInner.getMessage()!=null && tInner.getMessage().contains("Broken pipe")) {
  173.                 return true;
  174.             }
  175.         }
  176.        
  177.         return false;
  178.     }
  179.    
  180.     public static boolean isConnessioneServerReadTimeout(Throwable t){
  181.        
  182.         try {
  183.             java.net.SocketTimeoutException e = null;
  184.             if(t instanceof java.net.SocketTimeoutException){
  185.                 e = (java.net.SocketTimeoutException) t;
  186.             }
  187.             else if(Utilities.existsInnerException(t, java.net.SocketTimeoutException.class)){
  188.                 e = (java.net.SocketTimeoutException) Utilities.getInnerInstanceException(t, java.net.SocketTimeoutException.class, true);
  189.             }
  190.            
  191.             if(e!=null && e.getMessage()!=null && OpenSPCoop2Properties.getInstance().isServiceUnavailableReadTimedOut(e.getMessage())){
  192.                 return true;
  193.             }
  194.             else if(TimeoutIOException.isTimeoutIOException(t) && t.getMessage()!=null && t.getMessage().startsWith(CostantiPdD.PREFIX_TIMEOUT_RESPONSE)) {
  195.                 return true;
  196.             }
  197.            
  198.         }catch(Throwable tIgnore) {
  199.             // ignore
  200.         }
  201.        
  202.         return false;
  203.     }
  204.    
  205.     public static boolean isResponsePayloadTooLarge(Throwable t){
  206.         try {
  207.             if(LimitExceededIOException.isLimitExceededIOException(t) && t.getMessage()!=null && t.getMessage().startsWith(CostantiPdD.PREFIX_LIMITED_RESPONSE)) {
  208.                 return true;
  209.             }
  210.         }catch(Throwable tIgnore) {
  211.             // ignore
  212.         }
  213.        
  214.         return false;
  215.     }
  216.    
  217.     public static InformazioniErroriInfrastrutturali readInformazioniErroriInfrastrutturali(PdDContext pddContext){
  218.        
  219.         InformazioniErroriInfrastrutturali informazioniErrori = new InformazioniErroriInfrastrutturali();
  220.        
  221.         boolean erroreUtilizzoConnettore = false;
  222.         if(pddContext!=null){
  223.             Object o = pddContext.getObject(org.openspcoop2.core.constants.Costanti.ERRORE_UTILIZZO_CONNETTORE);
  224.             if(o instanceof Boolean){
  225.                 erroreUtilizzoConnettore = (Boolean) o;
  226.             }
  227.         }
  228.         informazioniErrori.setErroreUtilizzoConnettore(erroreUtilizzoConnettore);

  229.         boolean erroreSOAPFaultServerPortaDelegata = false;
  230.         if(pddContext!=null){
  231.             Object o = pddContext.getObject(org.openspcoop2.core.constants.Costanti.ERRORE_SOAP_FAULT_SERVER);
  232.             if(o instanceof Boolean){
  233.                 erroreSOAPFaultServerPortaDelegata = (Boolean) o;
  234.             }
  235.         }
  236.         informazioniErrori.setRicevutoSoapFaultServerPortaDelegata(erroreSOAPFaultServerPortaDelegata);
  237.        
  238.         boolean erroreContenutoRichiestaNonRiconosciuto = false;
  239.         if(pddContext!=null){
  240.             Object o = pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RICHIESTA_NON_RICONOSCIUTO);
  241.             if(o instanceof Boolean){
  242.                 erroreContenutoRichiestaNonRiconosciuto = (Boolean) o;
  243.             }
  244.         }
  245.         informazioniErrori.setContenutoRichiestaNonRiconosciuto(erroreContenutoRichiestaNonRiconosciuto);
  246.        
  247.         boolean erroreContenutoRispostaNonRiconosciuto = false;
  248.         if(pddContext!=null){
  249.             Object o = pddContext.getObject(org.openspcoop2.core.constants.Costanti.CONTENUTO_RISPOSTA_NON_RICONOSCIUTO);
  250.             if(o instanceof Boolean){
  251.                 erroreContenutoRispostaNonRiconosciuto = (Boolean) o;
  252.             }
  253.         }
  254.         informazioniErrori.setContenutoRispostaNonRiconosciuto(erroreContenutoRispostaNonRiconosciuto);
  255.        
  256.         return informazioniErrori;
  257.     }
  258.    
  259.    


  260.     public static String checkMustUnderstand(OpenSPCoop2SoapMessage message,IProtocolFactory<?> protocolFactory) throws MessageException{
  261.         SOAPEnvelope envelope = null;
  262.         SOAPHeader header = null;
  263.         try {
  264.             OpenSPCoop2Properties openspcoopProperties = OpenSPCoop2Properties.getInstance();

  265.             if(openspcoopProperties!=null){
  266.                 if(openspcoopProperties.isBypassFilterMustUnderstandEnabledForAllHeaders()){
  267.                     return null;
  268.                 }else{
  269.                    
  270.                     envelope = message.getSOAPPart().getEnvelope();
  271.                     header = envelope.getHeader();
  272.                    
  273.                     //Se non c'e' l'header il controllo e' inutile
  274.                     if(header == null) return null;
  275.                    
  276.                     List<NameValue> filtri = openspcoopProperties.getBypassFilterMustUnderstandProperties(protocolFactory.getProtocol());
  277.                     if(filtri!=null && !filtri.isEmpty()){
  278.                         return ServicesUtils.checkMustUnderstandHeaderElement(message.getMessageType(),header,filtri);
  279.                     }
  280.                 }
  281.             }

  282.         } catch (Exception ex) {
  283.            
  284.             Throwable t = ParseExceptionUtils.getParseException(ex);
  285.             if(t!=null){
  286.                 throw new MessageException(ex);
  287.             }
  288.            
  289.             if(Utilities.existsInnerException(ex, "com.ctc.wstx.exc.WstxUnexpectedCharException") || Utilities.existsInnerException(ex, "com.ctc.wstx.exc.WstxParsingException"))
  290.                 throw new MessageException(ex);
  291.             else
  292.                 throw new MessageException("BypassMustUnderstand, errore durante il set processed degli header con mustUnderstand='1' e actor non presente: "+ex.getMessage(),
  293.                     ex);
  294.         }  finally{
  295.             // *** GB ***
  296.             header = null;
  297.             envelope = null;
  298.             // *** GB ***
  299.         }      
  300.         return null;
  301.     }
  302.     private static String checkMustUnderstandHeaderElement(MessageType messageType, SOAPHeader header,List<NameValue> filtri) throws UtilsException{
  303.        
  304.         try{
  305.             StringBuilder bfError = new StringBuilder();
  306.             if(!SoapUtils.checkMustUnderstandHeaderElement(messageType, header, filtri, bfError)){
  307.                 return bfError.toString();
  308.             }
  309.             return null;
  310.         }catch(Exception e){
  311.             throw new UtilsException(e.getMessage(),e);
  312.         }
  313.        
  314.     }
  315.    
  316.     public static String checkSOAPEnvelopeNamespace(OpenSPCoop2SoapMessage message, MessageType messageType) throws MessageException{
  317.         try {
  318.             if(!SoapUtils.checkSOAPEnvelopeNamespace(message, messageType)){
  319.                
  320.                 OpenSPCoop2MessageSoapStreamReader reader = message.getSoapReader();
  321.                 String envelopeNamespace = null;
  322.                 if(reader!=null) {
  323.                     envelopeNamespace = reader.getNamespace();
  324.                 }
  325.                 if(envelopeNamespace==null) {
  326.                     return message.getSOAPPart().getEnvelope().getNamespaceURI();
  327.                 }
  328.                 else {
  329.                     return envelopeNamespace;
  330.                 }
  331.                
  332.             }
  333.             return null;
  334.         } catch (Exception ex) {
  335.             throw new MessageException("CheckSoapEnvelopeNamespace, errore durante il controllo del namespace del soap envelope: "+ex.getMessage(),ex);
  336.         }
  337.     }

  338.    
  339.     public static void checkCharset(String contentType, List<String> ctDefault, MsgDiagnostico msgDiag, boolean request, TipoPdD tipoPdD) throws MessageException {
  340.         try {
  341.             if(contentType!=null && contentType.contains(HttpConstants.CONTENT_TYPE_PARAMETER_CHARSET)){
  342.                 String charset = null;
  343.                 if(ContentTypeUtilities.isMultipartContentType(contentType)) {
  344.                     String ct = ContentTypeUtilities.getInternalMultipartContentType(charset);
  345.                     if(ct!=null) {
  346.                         charset = ContentTypeUtilities.readCharsetFromContentType(ct);
  347.                     }
  348.                 }
  349.                 else {
  350.                     charset = ContentTypeUtilities.readCharsetFromContentType(contentType);
  351.                 }
  352.                 if(charset!=null) {
  353.                     if(charset.startsWith("\"") && charset.length()>1) {
  354.                         charset = charset.substring(1);
  355.                     }
  356.                     if(charset.endsWith("\"") && charset.length()>1) {
  357.                         charset = charset.substring(0,charset.length()-1);
  358.                     }
  359.                 }
  360.                 boolean find = false;
  361.                 for (String def : ctDefault) {
  362.                     if(def.equalsIgnoreCase(charset)) {
  363.                         find = true;
  364.                         break;
  365.                     }
  366.                 }
  367.                 if(!find) {
  368.                     msgDiag.addKeyword(CostantiPdD.KEY_CONTENT_TYPE, contentType);
  369.                     StringBuilder sb = new StringBuilder();
  370.                     for (String def : ctDefault) {
  371.                         if(sb.length()>0) {
  372.                             sb.append(",");
  373.                         }
  374.                         sb.append(def);
  375.                     }
  376.                     msgDiag.addKeyword(CostantiPdD.KEY_CHARSET_DEFAULT, sb.toString());
  377.                     String idModuloFunzionale = TipoPdD.DELEGATA.equals(tipoPdD) ? MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_CONTENUTI_APPLICATIVI : MsgDiagnosticiProperties.MSG_DIAG_RICEZIONE_BUSTE;
  378.                     String idDiagnostico = request ? "richiesta.warningCharsetDifferenteDefault" : "risposta.warningCharsetDifferenteDefault";
  379.                     msgDiag.logPersonalizzato(idModuloFunzionale, idDiagnostico);
  380.                 }
  381.             }
  382.         } catch (Exception ex) {
  383.             throw new MessageException(ex.getMessage(),ex);
  384.         }
  385.     }

  386.    
  387.     public static boolean verificaRispostaRelazioneCodiceTrasporto202(IProtocolFactory<?> protocolFactory,OpenSPCoop2Properties openSPCoopProperties,
  388.             OpenSPCoop2Message responseMessage,boolean gestioneLatoPortaDelegata) throws ProtocolException, MessageException, MessageNotSupportedException {
  389.        
  390.         if(responseMessage==null){
  391.             return false;
  392.         }
  393.        
  394.         IProtocolManager protocolManager = protocolFactory.createProtocolManager();
  395.        
  396.         boolean rispostaPresente = true;
  397.         if(protocolManager.isHttpEmptyResponseOneWay()){
  398.             if(ServiceBinding.SOAP.equals(responseMessage.getServiceBinding())){
  399.                 OpenSPCoop2SoapMessage soap = responseMessage.castAsSoap();
  400.                
  401.                 if(soap.hasAttachments()) {
  402.                     rispostaPresente = true;
  403.                 }
  404.                 else {
  405.                     if(!soap.isSOAPBodyEmpty()) {
  406.                         rispostaPresente = true;
  407.                     }
  408.                     else {
  409.                    
  410.                         //potenziale msg inutile.
  411.                         Object h = null;
  412.                         SOAPHeader header = null;
  413.                         h = soap.getSOAPHeader();
  414.                         if(h!=null){
  415.                             header = (SOAPHeader) h;
  416.                         }
  417.                         if(h==null || header==null ||  SoapUtils.getFirstNotEmptyChildNode(responseMessage.getFactory(), header,false)==null ){
  418.                             /**System.out.println("MESSAGGIO INUTILE");*/
  419.                             rispostaPresente = false;
  420.                         }else{
  421.                             if(gestioneLatoPortaDelegata &&
  422.                                 !protocolManager.isHttpOneWay_PD_HTTPEmptyResponse() ) {
  423.                                 // E' possibile impostare una opzione che non torni nulla anche in questo caso
  424.                                 rispostaPresente = false;
  425.                             }
  426.                         }

  427.                        
  428.                         // *** GB ***
  429.                         header = null;
  430.                         h = null;
  431.                         // *** GB ***
  432.                     }
  433.                 }
  434.             }
  435.             else{
  436.                 /**OpenSPCoop2RestMessage<?> rest = responseMessage.castAsRest();
  437.                 if(rest.hasContent()==false){
  438.                     //System.out.println("MESSAGGIO VUOTO");
  439.                     rispostaPresente = false;
  440.                 }*/
  441.                 rispostaPresente = true; // La gestione del return code in REST è indipendente dal fatto se vi è o meno un contenuto
  442.             }
  443.         }
  444.        
  445.         return rispostaPresente;
  446.     }
  447.        
  448.    
  449.    
  450.     public static void setTransferLength(TransferLengthModes transferLengthMode,
  451.             ConnectorInMessage connectorInMessage, ConnectorOutMessage connectorOutMessage,
  452.             OpenSPCoop2Message message) throws ConnectorException, MessageException {
  453.         String requestProtocoll = connectorInMessage.getProtocol();
  454.         if(requestProtocoll!=null && requestProtocoll.endsWith("1.1")){
  455.             if(TransferLengthModes.TRANSFER_ENCODING_CHUNKED.equals(transferLengthMode)){
  456.                 connectorOutMessage.setHeader(HttpConstants.TRANSFER_ENCODING,HttpConstants.TRANSFER_ENCODING_VALUE_CHUNCKED);
  457.             }
  458.             else if(TransferLengthModes.CONTENT_LENGTH.equals(transferLengthMode) &&
  459.                 message!=null){
  460.                 message.writeTo(NullOutputStream.INSTANCE, false);
  461.                 connectorOutMessage.setContentLength((int)message.getOutgoingMessageContentLength());
  462.             }
  463.         }
  464.     }
  465.     public static void setTransferLength(TransferLengthModes transferLengthMode,
  466.             ConnectorInMessage connectorInMessage, ConnectorOutMessage connectorOutMessage,
  467.             Long length) throws ConnectorException {
  468.         String requestProtocoll = connectorInMessage.getProtocol();
  469.         if(requestProtocoll!=null && requestProtocoll.endsWith("1.1")){
  470.             if(TransferLengthModes.TRANSFER_ENCODING_CHUNKED.equals(transferLengthMode)){
  471.                 connectorOutMessage.setHeader(HttpConstants.TRANSFER_ENCODING,HttpConstants.TRANSFER_ENCODING_VALUE_CHUNCKED);
  472.             }
  473.             else if(TransferLengthModes.CONTENT_LENGTH.equals(transferLengthMode) &&
  474.                 length!=null){
  475.                 connectorOutMessage.setContentLength(length.intValue());
  476.             }
  477.         }
  478.     }
  479.    
  480.    
  481.     public static void setContentType(OpenSPCoop2Message message, ConnectorOutMessage connectorOutMessage) throws ConnectorException{
  482.         try{
  483.             if(CostantiPdD.isEnabledAddSWAStartParameterIfNotPresent(message)) {
  484.                 SoapUtils.addSWAStartParameterIfNotPresent(message);
  485.             }
  486.            
  487.             String contentTypeRisposta = message.getContentType();
  488.             if (contentTypeRisposta != null) {
  489.                 connectorOutMessage.setContentType(contentTypeRisposta);
  490.             }else {
  491.                 if(ServiceBinding.SOAP.equals(message.getServiceBinding())){
  492.                     throw new MessageException("Risposta errore senza Content-type");
  493.                 }
  494.                 else{
  495.                     if(message.castAsRest().hasContent()){
  496.                         throw new MessageException("Risposta errore senza Content-type");
  497.                     }
  498.                 }
  499.             }
  500.         }catch(Exception e){
  501.             throw new ConnectorException(e.getMessage(),e);
  502.         }  
  503.     }
  504.    
  505.    
  506.     public static void setGovWayHeaderResponse(ServiceBinding serviceBindingRequest, OpenSPCoop2Message msg, OpenSPCoop2Properties openspcoopProperties,
  507.             Map<String, List<String>> propertiesTrasporto, Logger logCore, boolean portaDelegata, PdDContext pddContext, RequestInfo requestInfo) {
  508.                
  509.         UtilitiesIntegrazione utilitiesIntegrazione = null;
  510.         try {                      
  511.             if(portaDelegata) {
  512.                 utilitiesIntegrazione = UtilitiesIntegrazione.getInstancePDResponse(logCore);
  513.             }
  514.             else {
  515.                 utilitiesIntegrazione = UtilitiesIntegrazione.getInstancePAResponse(logCore);
  516.             }
  517.            
  518.             List<String> idTransazioneValues = TransportUtils.getRawObject(propertiesTrasporto, Costanti.ID_TRANSAZIONE.getValue());
  519.            
  520.             if(idTransazioneValues==null || idTransazioneValues.isEmpty()) {
  521.                 String idTransazione = (String) pddContext.getObject(Costanti.ID_TRANSAZIONE);
  522.                 HeaderIntegrazione hdr = new HeaderIntegrazione(idTransazione);
  523.                 utilitiesIntegrazione.setTransportProperties(hdr,propertiesTrasporto,null);
  524.             }
  525.             else {
  526.                 utilitiesIntegrazione.setInfoProductTransportProperties(propertiesTrasporto);
  527.             }
  528.         }catch(Exception e){
  529.             logCore.error("Set header di integrazione fallito: "+e.getMessage(),e);
  530.         }
  531.         if(pddContext.containsKey(CostantiControlloTraffico.PDD_CONTEXT_HEADER_RATE_LIMITING)) {
  532.             Properties pHeaderRateLimiting = (Properties) pddContext.getObject(CostantiControlloTraffico.PDD_CONTEXT_HEADER_RATE_LIMITING);
  533.             if(pHeaderRateLimiting.size()>0) {
  534.                 java.util.Enumeration<?> en = pHeaderRateLimiting.keys();
  535.                 while(en.hasMoreElements()){
  536.                     String key = (String) en.nextElement();
  537.                     TransportUtils.setHeader(propertiesTrasporto,key, pHeaderRateLimiting.getProperty(key));
  538.                 }  
  539.             }
  540.         }
  541.                
  542.         setCORSAllowOrigin(propertiesTrasporto, logCore, portaDelegata, pddContext, requestInfo);
  543.            
  544.         // ------ inserisco gli headers peer -------
  545.         HeaderMap extraHeaders = Objects.requireNonNullElse(
  546.                 (HeaderMap) pddContext.getObject(CostantiPdD.EXTRA_HEADERS_RESPONSE),
  547.                 new HeaderMap());
  548.         extraHeaders.forEach((key, value) ->
  549.             TransportUtils.setHeader(propertiesTrasporto, key, value)
  550.         );
  551.        
  552.         try {
  553.                
  554.             OpenSPCoop2MessageProperties forwardHeader = null;
  555.             if(msg!=null &&
  556.                     openspcoopProperties!=null // Puo' non essere inizializzato
  557.                     ) {
  558.                 if(ServiceBinding.REST.equals(msg.getServiceBinding())) {
  559.                     forwardHeader = msg.getForwardTransportHeader(openspcoopProperties.getRESTServicesHeadersForwardConfig(false));
  560.                 }
  561.                 else {
  562.                     forwardHeader = msg.getForwardTransportHeader(openspcoopProperties.getSOAPServicesHeadersForwardConfig(false));
  563.                 }
  564.             }
  565.            
  566.             try {
  567.                 if(utilitiesIntegrazione!=null) {
  568.                     ServiceBinding sb = msg!=null ? msg.getServiceBinding() : serviceBindingRequest;
  569.                     utilitiesIntegrazione.setSecurityHeaders(sb, requestInfo, propertiesTrasporto, forwardHeader);
  570.                 }
  571.             }catch(Exception e){
  572.                 logCore.error("Set security headers fallito: "+e.getMessage(),e);
  573.             }
  574.            
  575.             if(propertiesTrasporto!=null && !propertiesTrasporto.isEmpty()) {
  576.                 if(forwardHeader!=null && forwardHeader.size()>0) {
  577.                     for (String key : propertiesTrasporto.keySet()) {
  578.                         forwardHeader.removePropertyValues(key);
  579.                     }
  580.                 }
  581.             }
  582.            
  583.         }catch(Exception e){
  584.             logCore.error("Pulizia forward header, rispetto a quelli generati da GovWay, fallito: "+e.getMessage(),e);
  585.         }
  586.     }
  587.    
  588.    
  589.    
  590.     private static void setCORSAllowOrigin(Map<String, List<String>> propertiesTrasporto, Logger logCore, boolean portaDelegata, PdDContext pddContext, RequestInfo requestInfo) {
  591.         try {
  592.            
  593.             Object nomePortaObject = pddContext.getObject(CostantiPdD.NOME_PORTA_INVOCATA);
  594.             String nomePorta = null;
  595.             if(nomePortaObject instanceof String) {
  596.                 nomePorta = (String) nomePortaObject;
  597.             }
  598.            
  599.             CorsConfigurazione cors = null;
  600.             HttpServletRequest httpServletRequest = null;
  601.             URLProtocolContext protocolContext = null;
  602.             if(requestInfo!=null) {
  603.                 protocolContext = requestInfo.getProtocolContext();
  604.             }
  605.             if(protocolContext!=null) {
  606.                 httpServletRequest = protocolContext.getHttpServletRequest();  
  607.                 if(nomePorta==null) {
  608.                     nomePorta = protocolContext.getInterfaceName();
  609.                 }
  610.             }
  611.            
  612.             if(httpServletRequest!=null) {
  613.                 ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance();
  614.                 if(nomePorta!=null) {
  615.                     if(portaDelegata) {
  616.                         IDPortaDelegata idPD = new IDPortaDelegata();
  617.                         idPD.setNome(nomePorta);
  618.                         PortaDelegata pdDefault = configurazionePdDManager.getPortaDelegataSafeMethod(idPD, requestInfo);
  619.                         cors = configurazionePdDManager.getConfigurazioneCORS(pdDefault);
  620.                     }
  621.                     else {
  622.                         IDPortaApplicativa idPA = new IDPortaApplicativa();
  623.                         idPA.setNome(nomePorta);
  624.                         PortaApplicativa paDefault = configurazionePdDManager.getPortaApplicativaSafeMethod(idPA, requestInfo);
  625.                         cors = configurazionePdDManager.getConfigurazioneCORS(paDefault);                      
  626.                     }
  627.                 }
  628.                 if(cors==null) {
  629.                     cors = configurazionePdDManager.getConfigurazioneCORS();
  630.                 }
  631.             }
  632.             else {
  633.                 cors = new CorsConfigurazione();
  634.                 cors.setStato(StatoFunzionalita.DISABILITATO);
  635.             }
  636.            
  637.             if(StatoFunzionalita.ABILITATO.equals(cors.getStato()) && TipoGestioneCORS.GATEWAY.equals(cors.getTipo())) {
  638.                 // verifico che non siamo in una preflight già gestita
  639.                 boolean preflightRequest = pddContext.containsKey(org.openspcoop2.core.constants.Costanti.CORS_PREFLIGHT_REQUEST_VIA_GATEWAY);
  640.                 if(!preflightRequest) {
  641.                     CORSFilter corsFilter = new CORSFilter(logCore, cors);
  642.                     CORSWrappedHttpServletResponse res = new CORSWrappedHttpServletResponse(false);
  643.                     corsFilter.doCORS(httpServletRequest, res, CORSRequestType.ACTUAL, true);
  644.                     propertiesTrasporto.putAll(res.getHeadersValues());
  645.                 }
  646.             }
  647.            
  648.         }catch(Exception e){
  649.             logCore.error("Set cors origin: "+e.getMessage(),e);
  650.         }

  651.     }
  652.    
  653.    
  654.     public static boolean isRequestWsdl(ConnectorInMessage reqParam, Logger logCore) {
  655.        
  656.         try {
  657.        
  658.             if(reqParam==null || reqParam.getURLProtocolContext()==null || reqParam.getURLProtocolContext().getHttpServletRequest()==null) {
  659.                 return false;
  660.             }
  661.             HttpServletRequest req = reqParam.getURLProtocolContext().getHttpServletRequest();
  662.            
  663.             if(HttpRequestMethod.GET.equals(req.getMethod())){
  664.                 Enumeration<?> parameters = req.getParameterNames();
  665.                 while(parameters.hasMoreElements()){
  666.                     String key = (String) parameters.nextElement();
  667.                     String value = req.getParameter(key);
  668.                     if("wsdl".equalsIgnoreCase(key) && (value==null || "".equals(value)) ){
  669.                         return true;
  670.                     }
  671.                 }
  672.             }
  673.            
  674.         }catch(Exception e){
  675.             logCore.error("IsRequestWsdl fallita: "+e.getMessage(),e);
  676.         }
  677.        
  678.         return false;
  679.     }
  680.    
  681.     public static void writeWsdl(ConnectorOutMessage response,RequestInfo requestInfo,
  682.             IDService idService, ServiceIdentificationReader serviceIdentificationReader, Logger logCore) throws ConnectorException {
  683.         try {
  684.            
  685.             boolean generazioneWsdlEnabled = false;
  686.             if(IDService.PORTA_APPLICATIVA.equals(idService)) {
  687.                 generazioneWsdlEnabled = OpenSPCoop2Properties.getInstance().isGenerazioneWsdlPortaApplicativaEnabled();
  688.             }
  689.             else {
  690.                 generazioneWsdlEnabled = OpenSPCoop2Properties.getInstance().isGenerazioneWsdlPortaDelegataEnabled();
  691.             }
  692.             if(!generazioneWsdlEnabled) {
  693.                 response.setStatus(404);
  694.                 response.sendResponse(DumpByteArrayOutputStream.newInstance(ConnectorUtils.generateError404Message(ConnectorUtils.getFullCodeWsdlUnsupported(idService)).getBytes()));
  695.                 return;
  696.             }
  697.            
  698.             byte [] wsdl = null;
  699.             if(requestInfo!=null && requestInfo.getIdServizio()!=null) {
  700.                 AccordoServizioParteSpecifica asps = null;
  701.                 AccordoServizioParteComune aspc = null;
  702.                 byte [] wsdlLogico = null;
  703.                 try {
  704.                     asps = serviceIdentificationReader.getRegistryReader().getAccordoServizioParteSpecifica(requestInfo.getIdServizio(), false);
  705.                 }catch(RegistryNotFound notFound) {}
  706.                 if(asps!=null) {
  707.                     try {
  708.                         IDAccordo idAccordo = IDAccordoFactory.getInstance().getIDAccordoFromUri(asps.getAccordoServizioParteComune());
  709.                         aspc = serviceIdentificationReader.getRegistryReader().getAccordoServizioParteComune(idAccordo, true, true);
  710.                     }catch(RegistryNotFound notFound) {}
  711.                 }
  712.                 if(aspc!=null) {
  713.                     if(TipologiaServizio.CORRELATO.equals(asps.getTipologiaServizio())){
  714.                         wsdlLogico = aspc.getByteWsdlLogicoFruitore();
  715.                     }
  716.                     else {
  717.                         wsdlLogico = aspc.getByteWsdlLogicoErogatore();
  718.                     }
  719.                 }
  720.                 if(wsdlLogico!=null) {
  721.                     // wsdl logico utilizzato dentro wsdlWrapperUtilities
  722.                     MessageXMLUtils xmlUtils = MessageXMLUtils.DEFAULT;
  723.                     WSDLUtilities wsdlUtilities = new WSDLUtilities(xmlUtils);
  724.                     AccordoServizioWrapperUtilities wsdlWrapperUtilities = new AccordoServizioWrapperUtilities(OpenSPCoop2MessageFactory.getDefaultMessageFactory(), logCore);
  725.                     wsdlWrapperUtilities.setAccordoServizio(new AccordoServizioWrapper());
  726.                     wsdlWrapperUtilities.getAccordoServizioWrapper().setAccordoServizio(aspc);
  727.                     javax.wsdl.Definition wsdlDefinition = null;
  728.                     if(TipologiaServizio.CORRELATO.equals(asps.getTipologiaServizio())){
  729.                         wsdlWrapperUtilities.getAccordoServizioWrapper().setBytesWsdlImplementativoFruitore(asps.getByteWsdlImplementativoFruitore());
  730.                         wsdlDefinition = wsdlWrapperUtilities.buildWsdlFruitoreFromBytes();
  731.                     }
  732.                     else {
  733.                         wsdlWrapperUtilities.getAccordoServizioWrapper().setBytesWsdlImplementativoErogatore(asps.getByteWsdlImplementativoErogatore());
  734.                         wsdlDefinition = wsdlWrapperUtilities.buildWsdlErogatoreFromBytes();
  735.                     }
  736.                    
  737.                     if(asps.getPortType()!=null && requestInfo.getProtocolContext()!=null) {
  738.                        
  739.                         UrlInvocazioneAPI urlInvocazioneApi = ConfigurazionePdDManager.getInstance().getConfigurazioneUrlInvocazione(requestInfo.getProtocolFactory(),
  740.                                  IDService.PORTA_APPLICATIVA.equals(idService) ? RuoloContesto.PORTA_APPLICATIVA : RuoloContesto.PORTA_DELEGATA,
  741.                                  requestInfo.getIntegrationServiceBinding(),
  742.                                  requestInfo.getProtocolContext().getInterfaceName(),
  743.                                  requestInfo.getIdentitaPdD(),
  744.                                  aspc,
  745.                                  requestInfo);      
  746.                         String prefixGatewayUrl = urlInvocazioneApi.getBaseUrl();
  747.                         String contesto = urlInvocazioneApi.getContext();
  748.                         prefixGatewayUrl = Utilities.buildUrl(prefixGatewayUrl, contesto);
  749.                         DefinitionWrapper wrapper = new DefinitionWrapper(wsdlDefinition, xmlUtils);
  750.                         PortType ptWSDL = wrapper.getPortType(asps.getPortType());
  751.                         if(ptWSDL!=null && ptWSDL.getQName()!=null && ptWSDL.getQName().getLocalPart()!=null) {
  752.                             Binding bindingWSDL = wrapper.getBindingByPortType(ptWSDL.getQName().getLocalPart());
  753.                             if(bindingWSDL!=null && bindingWSDL.getQName()!=null && bindingWSDL.getQName().getLocalPart()!=null) {
  754.                                 Port portWSDL = wrapper.getServicePortByBindingName(bindingWSDL.getQName().getLocalPart());
  755.                                 if(portWSDL!=null) {
  756.                                     wrapper.updateLocation(portWSDL, prefixGatewayUrl);
  757.                                 }
  758.                             }
  759.                         }
  760.                     }
  761.                    
  762.                    
  763.                     ByteArrayOutputStream bout = new ByteArrayOutputStream();
  764.                     wsdlUtilities.writeWsdlTo(wsdlDefinition, bout);
  765.                     bout.flush();
  766.                     bout.close();
  767.                     wsdl = bout.toByteArray();
  768.                 }
  769.             }
  770.            
  771.             if(wsdl!=null) {
  772.                 HttpUtilities.setOutputFile(new ConnectorHttpServletResponse(response), true, "interface.wsdl");    
  773.                 response.setStatus(200);
  774.                 response.sendResponse(DumpByteArrayOutputStream.newInstance(wsdl));
  775.             }
  776.             else {
  777.                 response.setStatus(404);
  778.                 response.sendResponse(DumpByteArrayOutputStream.newInstance(ConnectorUtils.generateError404Message(ConnectorUtils.getFullCodeWsdlNotDefined(idService)).getBytes()));
  779.             }
  780.            
  781.         }catch(Exception e){
  782.             logCore.error("Lettura wsdl fallita: "+e.getMessage(),e);
  783.             throw new ConnectorException("Lettura wsdl fallita: "+e.getMessage(),e);
  784.         }
  785.     }
  786.    
  787.    
  788.     public static void processTrackingException(Exception e, Logger log, FaseTracciamento fase, Context context) throws HandlerException {
  789.         HandlerException he = null;
  790.         if(e instanceof HandlerException) {
  791.             he = (HandlerException) e;
  792.             if(he.getIntegrationFunctionError()==null) {
  793.                 he.setIntegrationFunctionError(IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE);
  794.                 String msg = "Tracciamento '"+fase.name()+"' fallito: "+e.getMessage();
  795.                 log.error(msg,e);
  796.             }
  797.         }
  798.         else {
  799.             he = new HandlerException();
  800.             he.setIntegrationFunctionError(IntegrationFunctionError.GOVWAY_RESOURCES_NOT_AVAILABLE);
  801.             String msg = "Tracciamento '"+fase.name()+"' fallito: "+e.getMessage();
  802.             log.error(msg,e);
  803.         }
  804.         context.addObject(org.openspcoop2.core.constants.Costanti.ERRORE_TRACCIAMENTO, "true");
  805.         throw he;
  806.     }
  807.    
  808.     public static EsitoTransazione updateEsitoConAnomalie(EsitoTransazione esito, Logger log, IProtocolFactory<?> protocolFactory) {
  809.         try {
  810.             if(EsitoTransazioneName.OK.equals(esito.getName())) {
  811.                 EsitiProperties esitiProperties = EsitiProperties.getInstance(log, protocolFactory);
  812.                 esito = esitiProperties.convertToEsitoTransazione(EsitoTransazioneName.OK_PRESENZA_ANOMALIE, esito.getContextType());
  813.             }
  814.         }catch(Exception e) {
  815.             String msg = "Update esito con anomalie fallito: "+e.getMessage();
  816.             log.error(msg,e);
  817.         }
  818.         return esito;
  819.     }
  820.    
  821.     public static void initCheckConnectionDB(Logger logR, boolean checkIsClosed, boolean checkAutoCommit) {
  822.         DriverConfigurazioneDB.setCheckLogger(logR);
  823.         DriverConfigurazioneDB.setCheckIsClosed(checkIsClosed);
  824.         DriverConfigurazioneDB.setCheckAutocommit(checkAutoCommit);
  825.         DriverRegistroServiziDB.setCheckLogger(logR);
  826.         DriverRegistroServiziDB.setCheckIsClosed(checkIsClosed);
  827.         DriverRegistroServiziDB.setCheckAutocommit(checkAutoCommit);
  828.         JDBCServiceManagerBase.setCheckLogger(logR);
  829.         JDBCServiceManagerBase.setCheckIsClosed(checkIsClosed);
  830.         JDBCServiceManagerBase.setCheckAutocommit(checkAutoCommit);
  831.         BasicComponentFactory.setCheckLogger(logR);
  832.         BasicComponentFactory.setCheckIsClosed(checkIsClosed);
  833.         BasicComponentFactory.setCheckAutocommit(checkAutoCommit);
  834.         IDSerialGenerator.setCheckLogger(logR);
  835.         IDSerialGenerator.setCheckIsClosed(checkIsClosed);
  836.         IDSerialGenerator.setCheckAutocommit(checkAutoCommit);
  837.         org.openspcoop2.utils.datasource.DataSource.setCheckLogger(logR);
  838.         org.openspcoop2.utils.datasource.DataSource.setCheckIsClosed(checkIsClosed);
  839.         org.openspcoop2.utils.datasource.DataSource.setCheckAutocommit(checkAutoCommit);
  840.     }
  841. }

  842. class ConnectorHttpServletResponse extends WrappedHttpServletResponse {

  843.     @Override
  844.     public void setContentType(String type) {
  845.         try {
  846.             this.outMessage.setContentType(type);
  847.         }catch(Exception e) {
  848.             throw new UtilsRuntimeException(e.getMessage(),e);
  849.         }
  850.     }

  851.     @Override
  852.     public void setDateHeader(String arg0, long arg1) {
  853.         try {
  854.             this.outMessage.setHeader(arg0, arg1+"");
  855.         }catch(Exception e) {
  856.             throw new UtilsRuntimeException(e.getMessage(),e);
  857.         }
  858.     }

  859.     @Override
  860.     public void setHeader(String arg0, String arg1) {
  861.         try {
  862.             this.outMessage.setHeader(arg0, arg1);
  863.         }catch(Exception e) {
  864.             throw new UtilsRuntimeException(e.getMessage(),e);
  865.         }
  866.     }
  867.    
  868.     @Override
  869.     public void addHeader(String arg0, String arg1) {
  870.         try {
  871.             this.outMessage.addHeader(arg0, arg1);
  872.         }catch(Exception e) {
  873.             throw new UtilsRuntimeException(e.getMessage(),e);
  874.         }
  875.     }

  876.     private ConnectorOutMessage outMessage;
  877.    
  878.     public ConnectorHttpServletResponse(ConnectorOutMessage outMessage) {
  879.         super(null);
  880.         this.outMessage = outMessage;
  881.     }
  882.    
  883. }