ConnettoreSAAJ.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.connettori;

  21. import java.net.HttpURLConnection;
  22. import java.net.URL;
  23. import java.net.URLConnection;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;

  29. import javax.xml.soap.MimeHeader;
  30. import javax.xml.soap.SOAPConnection;
  31. import javax.xml.soap.SOAPConnectionFactory;
  32. import javax.xml.soap.SOAPMessage;

  33. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  34. import org.openspcoop2.core.constants.CostantiConnettori;
  35. import org.openspcoop2.core.transazioni.constants.TipoMessaggio;
  36. import org.openspcoop2.message.MessageUtils;
  37. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  38. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  39. import org.openspcoop2.message.constants.Costanti;
  40. import org.openspcoop2.message.constants.MessageRole;
  41. import org.openspcoop2.message.constants.MessageType;
  42. import org.openspcoop2.message.constants.ServiceBinding;
  43. import org.openspcoop2.pdd.config.CostantiProprieta;
  44. import org.openspcoop2.pdd.core.Utilities;
  45. import org.openspcoop2.pdd.mdb.ConsegnaContenutiApplicativi;
  46. import org.openspcoop2.utils.UtilsException;
  47. import org.openspcoop2.utils.date.DateManager;
  48. import org.openspcoop2.utils.io.Base64Utilities;
  49. import org.openspcoop2.utils.io.DumpByteArrayOutputStream;
  50. import org.openspcoop2.utils.resources.Charset;
  51. import org.openspcoop2.utils.transport.TransportResponseContext;
  52. import org.openspcoop2.utils.transport.TransportUtils;
  53. import org.openspcoop2.utils.transport.http.HttpConstants;
  54. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  55. import org.openspcoop2.utils.transport.http.HttpUtilities;
  56. import org.openspcoop2.utils.transport.http.RFC2047Encoding;
  57. import org.openspcoop2.utils.transport.http.RFC2047Utilities;

  58. /**
  59.  * Classe utilizzata per effettuare consegne di messaggi Soap, attraverso
  60.  * l'invocazione di un server http.
  61.  *
  62.  *
  63.  * @author Poli Andrea (apoli@link.it)
  64.  * @author $Author$
  65.  * @version $Rev$, $Date$
  66.  */

  67. public class ConnettoreSAAJ extends ConnettoreBaseWithResponse {

  68.     @Override
  69.     public String getProtocollo() {
  70.         return "HTTP";
  71.     }
  72.    
  73.     public static final String ENDPOINT_TYPE = "saaj";
  74.    

  75.     /** Connessione */
  76.     private SOAPConnection connection = null;

  77.     private SOAPMessage soapRequestMessage = null;
  78.    
  79.    
  80.     /* ********  METODI  ******** */

  81.     @Override
  82.     protected boolean initializePreSend(ResponseCachingConfigurazione responseCachingConfig, ConnettoreMsg request) {
  83.        
  84.         if(this.initialize(request, true, responseCachingConfig)==false){
  85.             return false;
  86.         }
  87.        
  88.         return true;
  89.        
  90.     }
  91.    
  92.     @Override
  93.     protected boolean send(ConnettoreMsg request) {

  94.         // analsi i parametri specifici per il connettore
  95.         if(this.properties.get(CostantiConnettori.CONNETTORE_LOCATION)==null){
  96.             this.errore = "Proprieta' '"+CostantiConnettori.CONNETTORE_LOCATION+"' non fornita e richiesta da questo tipo di connettore ["+request.getTipoConnettore()+"]";
  97.             return false;
  98.         }

  99.         return sendSAAJ();

  100.     }


  101.     /**
  102.      * Si occupa di effettuare la consegna SOAP (invocazione di un WebService).
  103.      * Si aspetta di ricevere una risposta non sbustata.
  104.      *
  105.      * @return true in caso di consegna con successo, false altrimenti
  106.      *
  107.      */
  108.     private boolean sendSAAJ(){
  109.         int connectionTimeout = -1;
  110.         boolean connectionTimeoutConfigurazioneGlobale = true;
  111.         int readConnectionTimeout = -1;
  112.         boolean readConnectionTimeoutConfigurazioneGlobale = true;
  113.         try{
  114.             // Impostazione timeout
  115.             if(this.debug)
  116.                 this.logger.debug("Impostazione timeout...");
  117.             if(this.properties.get(CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT)!=null){
  118.                 try{
  119.                     connectionTimeout = Integer.parseInt(this.properties.get(CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT));
  120.                     connectionTimeoutConfigurazioneGlobale = this.properties.containsKey(CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT_GLOBALE);
  121.                 }catch(Exception e){
  122.                     this.logger.error("Parametro '"+CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT+"' errato",e);
  123.                 }
  124.             }
  125.             if(connectionTimeout==-1){
  126.                 connectionTimeout = HttpUtilities.HTTP_CONNECTION_TIMEOUT;
  127.             }
  128.             if(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT)!=null){
  129.                 try{
  130.                     readConnectionTimeout = Integer.parseInt(this.properties.get(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT));
  131.                     readConnectionTimeoutConfigurazioneGlobale = this.properties.containsKey(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT_GLOBALE);
  132.                 }catch(Exception e){
  133.                     this.logger.error("Parametro '"+CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT+"' errato",e);
  134.                 }
  135.             }
  136.             if(readConnectionTimeout==-1){
  137.                 readConnectionTimeout = HttpUtilities.HTTP_READ_CONNECTION_TIMEOUT;
  138.             }
  139.             if(this.debug)
  140.                 this.logger.info("Impostazione http timeout CT["+connectionTimeout+"] RT["+readConnectionTimeout+"]...",false);
  141.            
  142.             // check validity message
  143.             if(ServiceBinding.SOAP.equals(this.requestMsg.getServiceBinding())==false) {
  144.                 throw new Exception("Connettore utilizzabile solamente in un contesto SOAP (trovato: "+this.requestMsg.getServiceBinding()+")");
  145.             }
  146.            
  147.             // check validita URL
  148.             if(this.debug)
  149.                 this.logger.debug("Check validita URL...");
  150.             this.location = this.properties.get(CostantiConnettori.CONNETTORE_LOCATION);
  151.             this.location = ConnettoreUtils.buildLocationWithURLBasedParameter(this.logger!=null ? this.logger.getLogger() : null, this.requestMsg, ENDPOINT_TYPE, this.propertiesUrlBased, this.location,
  152.                     this.getProtocolFactory(), this.idModulo);
  153.            
  154.             URL urlTest = new URL( this.location );
  155.             URLConnection connectionTest = urlTest.openConnection();
  156.             HttpURLConnection httpConnTest = (HttpURLConnection) connectionTest;
  157.             httpConnTest.setRequestMethod( HttpRequestMethod.POST.name() );
  158.             httpConnTest.setConnectTimeout(connectionTimeout);
  159.             httpConnTest.setReadTimeout(readConnectionTimeout);
  160.             httpConnTest.setDoOutput(true);
  161.             java.io.OutputStream outTest = httpConnTest.getOutputStream();
  162.             outTest.close();
  163.             httpConnTest.disconnect();

  164.            
  165.            
  166.             // Check tipo di messaggio
  167.             MessageType requestMessageType = this.requestMsg.getMessageType();
  168.             if(ServiceBinding.SOAP.equals(this.requestMsg.getServiceBinding())==false){
  169.                 throw new Exception("Connettore utilizzabile solamente per tipologia di servizio SOAP");
  170.             }
  171.             OpenSPCoop2SoapMessage soapRequestMessage = this.requestMsg.castAsSoap();
  172.             this.soapRequestMessage = MessageUtils.getSOAPMessage(soapRequestMessage, false, this.idTransazione);

  173.             // Collezione header di trasporto per dump
  174.             Map<String, List<String>> propertiesTrasportoDebug = null;
  175.             if(this.isDumpBinarioRichiesta()) {
  176.                 propertiesTrasportoDebug = new HashMap<>();
  177.             }
  178.            
  179.            
  180.             // impostazione property
  181.             if(this.debug)
  182.                 this.logger.debug("PrefixOptimization...");
  183.             String prefixOptimization = "true";
  184.             if(this.properties.get("prefix-optimization")!=null){
  185.                 if("false".equalsIgnoreCase(this.properties.get("prefix-optimization")) )
  186.                     prefixOptimization = "false";
  187.                 this.logger.info("Prefix Optimization = '"+prefixOptimization+"'",false);
  188.                 //AxisProperties.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,prefixOptimization);          
  189.             }
  190.            

  191.             // Consegna
  192.             if(this.debug)
  193.                 this.logger.debug("Creazione connessione...");  
  194.             OpenSPCoop2MessageFactory messageFactory = Utilities.getOpenspcoop2MessageFactory(this.logger.getLogger(),this.requestMsg, this.requestInfo, MessageRole.NONE);
  195.             SOAPConnectionFactory soapConnFactory = messageFactory.getSOAPConnectionFactory();
  196.             this.connection = soapConnFactory.createConnection();
  197.                                
  198.            
  199.             try{
  200.                 // Impostazione Proprieta del trasporto
  201.                
  202.                 // Impostazione Content-Type
  203.                 String contentTypeRichiesta = null;
  204.                 if(this.debug)
  205.                     this.logger.debug("Impostazione content type...");
  206.                 if(this.isSoap){
  207.                     contentTypeRichiesta = this.requestMsg.getContentType();
  208.                     if(contentTypeRichiesta==null){
  209.                         throw new Exception("Content-Type del messaggio da spedire non definito");
  210.                     }
  211.                 }
  212.                 else{
  213.                     contentTypeRichiesta = this.requestMsg.getContentType();
  214.                     // Content-Type non obbligatorio in REST
  215.                 }
  216.                 if(this.debug)
  217.                     this.logger.info("Impostazione Content-Type ["+contentTypeRichiesta+"]",false);
  218.                 if(contentTypeRichiesta!=null){
  219.                     setRequestHeader(HttpConstants.CONTENT_TYPE, contentTypeRichiesta, propertiesTrasportoDebug);
  220.                 }
  221.                
  222.                

  223.                 // Authentication BASIC
  224.                 if(this.debug)
  225.                     this.logger.debug("Impostazione autenticazione...");
  226.                 String user = null;
  227.                 String password = null;
  228.                 if(this.credenziali!=null){
  229.                     user = this.credenziali.getUser();
  230.                     password = this.credenziali.getPassword();
  231.                 }else{
  232.                     user = this.properties.get(CostantiConnettori.CONNETTORE_USERNAME);
  233.                     password = this.properties.get(CostantiConnettori.CONNETTORE_PASSWORD);
  234.                 }
  235.                 if(user!=null && password!=null){
  236.                     String authentication = user + ":" + password;
  237.                     authentication = HttpConstants.AUTHORIZATION_PREFIX_BASIC + Base64Utilities.encodeAsString(authentication.getBytes());
  238.                     setRequestHeader(HttpConstants.AUTHORIZATION,authentication, propertiesTrasportoDebug);
  239.                     if(this.debug)
  240.                         this.logger.info("Impostazione autenticazione (username:"+user+" password:"+password+") ["+authentication+"]",false);
  241.                 }
  242.                
  243.                 // Impostazione timeout
  244.                 if(this.debug)
  245.                     this.logger.debug("Set timeout...");
  246.                 //TODO: connection.setTimeout(readConnectionTimeout);
  247.                
  248.                
  249.                
  250.                 // Impostazione Proprieta del trasporto
  251.                 if(this.debug)
  252.                     this.logger.debug("Impostazione header di trasporto...");
  253.                 boolean encodingRFC2047 = false;
  254.                 Charset charsetRFC2047 = null;
  255.                 RFC2047Encoding encodingAlgorithmRFC2047 = null;
  256.                 boolean validazioneHeaderRFC2047 = false;
  257.                 if(this.idModulo!=null){
  258.                     if(ConsegnaContenutiApplicativi.ID_MODULO.equals(this.idModulo)){
  259.                         encodingRFC2047 = this.openspcoopProperties.isEnabledEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  260.                         charsetRFC2047 = this.openspcoopProperties.getCharsetEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  261.                         encodingAlgorithmRFC2047 = this.openspcoopProperties.getEncodingRFC2047HeaderValueConsegnaContenutiApplicativi();
  262.                         validazioneHeaderRFC2047 = this.openspcoopProperties.isEnabledValidazioneRFC2047HeaderNameValueConsegnaContenutiApplicativi();
  263.                     }else{
  264.                         encodingRFC2047 = this.openspcoopProperties.isEnabledEncodingRFC2047HeaderValueInoltroBuste();
  265.                         charsetRFC2047 = this.openspcoopProperties.getCharsetEncodingRFC2047HeaderValueInoltroBuste();
  266.                         encodingAlgorithmRFC2047 = this.openspcoopProperties.getEncodingRFC2047HeaderValueInoltroBuste();
  267.                         validazioneHeaderRFC2047 = this.openspcoopProperties.isEnabledValidazioneRFC2047HeaderNameValueInoltroBuste();
  268.                     }
  269.                    
  270.                     encodingRFC2047 = CostantiProprieta.isConnettoriHeaderValueEncodingRFC2047RequestEnabled(this.proprietaPorta, encodingRFC2047);
  271.                     charsetRFC2047 = CostantiProprieta.getConnettoriHeaderValueEncodingRFC2047RequestCharset(this.proprietaPorta, charsetRFC2047);
  272.                     encodingAlgorithmRFC2047 = CostantiProprieta.getConnettoriHeaderValueEncodingRFC2047RequestType(this.proprietaPorta, encodingAlgorithmRFC2047);
  273.                     validazioneHeaderRFC2047 = CostantiProprieta.isConnettoriHeaderValidationRequestEnabled(this.proprietaPorta, validazioneHeaderRFC2047);
  274.                 }
  275.                 this.forwardHttpRequestHeader();
  276.                 if(this.propertiesTrasporto != null){
  277.                     Iterator<String> keys = this.propertiesTrasporto.keySet().iterator();
  278.                     while (keys.hasNext()) {
  279.                         String key = (String) keys.next();
  280.                         if(HttpConstants.USER_AGENT.equalsIgnoreCase(key)){
  281.                             continue;
  282.                         }
  283.                         List<String> values = this.propertiesTrasporto.get(key);
  284.                         if(this.debug) {
  285.                             if(values!=null && !values.isEmpty()) {
  286.                                 for (String value : values) {
  287.                                     this.logger.info("Set Transport Header ["+key+"]=["+value+"]",false);
  288.                                 }
  289.                             }
  290.                         }
  291.                        
  292.                         if(encodingRFC2047){
  293.                             List<String> valuesEncoded = new ArrayList<>();
  294.                             if(values!=null && !values.isEmpty()) {
  295.                                 for (String value : values) {
  296.                                     if(RFC2047Utilities.isAllCharactersInCharset(value, charsetRFC2047)==false){
  297.                                         String encoded = RFC2047Utilities.encode(new String(value), charsetRFC2047, encodingAlgorithmRFC2047);
  298.                                         //System.out.println("@@@@ CODIFICA ["+value+"] in ["+encoded+"]");
  299.                                         if(this.debug)
  300.                                             this.logger.info("RFC2047 Encoded value in ["+encoded+"] (charset:"+charsetRFC2047+" encoding-algorithm:"+encodingAlgorithmRFC2047+")",false);
  301.                                         valuesEncoded.add(encoded);
  302.                                     }
  303.                                     else{
  304.                                         valuesEncoded.add(value);
  305.                                     }
  306.                                 }
  307.                             }
  308.                             setRequestHeader(validazioneHeaderRFC2047, key, valuesEncoded, this.logger, propertiesTrasportoDebug);
  309.                         }
  310.                         else{
  311.                             setRequestHeader(validazioneHeaderRFC2047, key, values, this.logger, propertiesTrasportoDebug);
  312.                         }
  313.                     }
  314.                 }
  315.                
  316.                
  317.                
  318.                
  319.                 // Aggiunta del SoapAction Header in caso di richiesta SOAP
  320.                 // spostato sotto il forwardHeader per consentire alle trasformazioni di modificarla
  321.                 if(this.isSoap && this.sbustamentoSoap == false){
  322.                     if(this.debug)
  323.                         this.logger.debug("Impostazione soap action...");
  324.                     boolean existsTransportProperties = false;
  325.                     if(TransportUtils.containsKey(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION)){
  326.                         this.soapAction = TransportUtils.getFirstValue(this.propertiesTrasporto, Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION);
  327.                         existsTransportProperties = (this.soapAction!=null);
  328.                     }
  329.                     if(!existsTransportProperties) {
  330.                         this.soapAction = soapRequestMessage.getSoapAction();
  331.                     }
  332.                     if(this.soapAction==null){
  333.                         this.soapAction="\"OpenSPCoop\"";
  334.                     }
  335.                     if(MessageType.SOAP_11.equals(this.requestMsg.getMessageType()) && !existsTransportProperties){
  336.                         // NOTA non quotare la soap action, per mantenere la trasparenza della PdD
  337.                         setRequestHeader(Costanti.SOAP11_MANDATORY_HEADER_HTTP_SOAP_ACTION,this.soapAction, propertiesTrasportoDebug);
  338.                     }
  339.                     if(this.debug)
  340.                         this.logger.info("SOAP Action inviata ["+this.soapAction+"]",false);
  341.                 }
  342.                
  343.                
  344.                
  345.                 if(this.isDumpBinarioRichiesta()) {
  346.                     DumpByteArrayOutputStream bout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  347.                             TipoMessaggio.RICHIESTA_USCITA_DUMP_BINARIO.getValue());
  348.                     try {
  349.                         this.emitDiagnosticStartDumpBinarioRichiestaUscita();
  350.                        
  351.                         this.requestMsg.writeTo(bout, false);
  352.                         bout.flush();
  353.                         bout.close();
  354.                        
  355.                         this.dumpBinarioRichiestaUscita(bout, requestMessageType, contentTypeRichiesta, this.location, propertiesTrasportoDebug);
  356.                     }finally {
  357.                         try {
  358.                             bout.clearResources();
  359.                         }catch(Throwable t) {
  360.                             this.logger.error("Release resources failed: "+t.getMessage(),t);
  361.                         }
  362.                     }
  363.                 }
  364.                                
  365.                 // Send
  366.                 if(this.debug)
  367.                     this.logger.debug("Send...");
  368.                
  369.                 SOAPMessage soapMsg = this.connection.call( this.soapRequestMessage, this.location);
  370.                
  371.                 this.dataRichiestaInoltrata = DateManager.getDate();
  372.                
  373.                 this.responseMsg = messageFactory.
  374.                         createMessage(this.requestMsg.getMessageType(),MessageRole.RESPONSE,soapMsg);
  375.                
  376.                 this.dataAccettazioneRisposta = DateManager.getDate();
  377.                
  378.             }catch(javax.xml.soap.SOAPException sendError){
  379.                 this.eccezioneProcessamento = sendError;
  380.                 String errorMsg = this.readExceptionMessageFromException(sendError);
  381.                 this.connection.close();
  382.                 this.errore = "Errore avvenuto durante la consegna SOAP (lettura risposta): " + errorMsg;
  383.                 return false;
  384.             }

  385.             // check consistenza risposta
  386.             if(this.debug)
  387.                 this.logger.debug("Check consistenza...");
  388.             SOAPMessage soapResponse = null;
  389.             if(this.responseMsg!=null){
  390.                 OpenSPCoop2SoapMessage soapMessageResponse = this.responseMsg.castAsSoap();
  391.                 soapResponse = soapMessageResponse.getSOAPMessage();
  392.                 if(soapMessageResponse.getSOAPBody()!=null){
  393.                     if(soapMessageResponse.hasSOAPFault() ){
  394.                         if(soapMessageResponse.getSOAPBody().getFault().getFaultString().indexOf("Premature end of file") != -1){
  395.                             // L'errore 'premature end of file' consiste solo nel fatto che una risposta non e' stata ricevuta.
  396.                             this.responseMsg = null;
  397.                         }
  398.                     }
  399.                 }
  400.             }

  401.             if(soapResponse!=null){
  402.                 // Analisi MimeType e ContentLocation della risposta
  403.                 if(soapResponse.getMimeHeaders()!=null){
  404.                    
  405.                     if(this.propertiesTrasportoRisposta==null){
  406.                         this.propertiesTrasportoRisposta = new HashMap<>();
  407.                     }
  408.                    
  409.                     Iterator<?> it = soapResponse.getMimeHeaders().getAllHeaders();
  410.                     while (it.hasNext()) {
  411.                         MimeHeader mh = (MimeHeader) it.next();
  412.                         if(mh!=null && mh.getName()!=null && mh.getValue()!=null) {
  413.                             TransportUtils.addHeader(this.propertiesTrasportoRisposta,mh.getName(),mh.getValue());
  414.                             if("content-length".equalsIgnoreCase(mh.getName())){
  415.                                 try{
  416.                                     this.contentLength = Integer.parseInt(mh.getValue());
  417.                                 }catch(Exception e){}
  418.                             }
  419.                             if("content-type".equalsIgnoreCase(mh.getName())){
  420.                                 try{
  421.                                     this.tipoRisposta = mh.getValue();
  422.                                 }catch(Exception e){}
  423.                             }
  424.                         }
  425.                     }
  426.                 }
  427.             }
  428.            
  429.             // return code
  430.             this.codice = 200;

  431.             // content length
  432.             if(this.responseMsg!=null && this.contentLength<0){
  433.                 this.contentLength =  this.responseMsg.getIncomingMessageContentLength();
  434.             }
  435.            
  436.             if(this.responseMsg!=null){
  437.                 TransportResponseContext responseContext = new TransportResponseContext(this.logger.getLogger());
  438.                 responseContext.setCodiceTrasporto(this.codice+"");
  439.                 responseContext.setContentLength(this.contentLength);
  440.                 responseContext.setHeaders(this.propertiesTrasportoRisposta);
  441.                 this.responseMsg.setTransportResponseContext(responseContext);
  442.                
  443.                 this.messageTypeResponse = this.requestMsg.getMessageType();
  444.                 if(this.tipoRisposta==null) {
  445.                     this.tipoRisposta = this.requestMsg.getContentType();
  446.                 }
  447.             }
  448.            
  449.             if(this.isDumpBinarioRisposta()){
  450.                 if(this.responseMsg!=null){
  451.                     // Registro Debug.
  452.                     DumpByteArrayOutputStream bout = null;
  453.                     try {
  454.                         try {
  455.                             bout = new DumpByteArrayOutputStream(this.dumpBinario_soglia, this.dumpBinario_repositoryFile, this.idTransazione,
  456.                                     TipoMessaggio.RISPOSTA_INGRESSO_DUMP_BINARIO.getValue());
  457.                            
  458.                             this.emitDiagnosticStartDumpBinarioRispostaIngresso();
  459.                            
  460.                             this.responseMsg.writeTo(bout, false);
  461.                         }finally {
  462.                             try {
  463.                                 if(bout!=null) {
  464.                                     bout.flush();
  465.                                 }
  466.                             }catch(Throwable t) {
  467.                                 // ignore
  468.                             }
  469.                             try {
  470.                                 if(bout!=null) {
  471.                                     bout.close();
  472.                                 }
  473.                             }catch(Throwable t) {
  474.                                 // ignore
  475.                             }
  476.                         }
  477.                         if(this.debug) {
  478.                             this.logger.info("Messaggio ricevuto (ContentType:"+this.tipoRisposta+") :\n"+bout.toString(),false);
  479.                         }
  480.                        
  481.                         this.dumpBinarioRispostaIngresso(bout, this.messageTypeResponse, this.propertiesTrasportoRisposta);
  482.                        
  483.                         if(this.contentLength<0){
  484.                             this.contentLength=bout.size(); // la prendo dal dump, poiche' in saaj non ho modo di agganciare il counting stream
  485.                         }
  486.                        
  487.                     }finally {
  488.                         try {
  489.                             if(bout!=null) {
  490.                                 bout.clearResources();
  491.                             }
  492.                         }catch(Throwable t) {
  493.                             this.logger.error("Release resources failed: "+t.getMessage(),t);
  494.                         }
  495.                     }
  496.                 }
  497.                 else {
  498.                     if(this.debug) {
  499.                         if(this.tipoRisposta!=null) {
  500.                             this.logger.info("Messaggio ricevuto (ContentType:"+this.tipoRisposta+") senza contenuto nell'http-reply",false);
  501.                         }
  502.                         else {
  503.                             this.logger.info("Messaggio ricevuto senza contenuto nell'http-reply",false);
  504.                         }
  505.                     }
  506.                    
  507.                     // devo registrare almeno gli header HTTP
  508.                     this.emitDiagnosticStartDumpBinarioRispostaIngresso();
  509.                     this.dumpBinarioRispostaIngresso(null, null, this.propertiesTrasportoRisposta);
  510.                 }
  511.             }
  512.            
  513.            
  514.             if(this.debug)
  515.                 this.logger.info("Gestione invio/risposta http effettuata con successo",false);
  516.            
  517.            
  518.            
  519.            
  520.            
  521.             /* ------------  PostOutRequestHandler ------------- */
  522.             this.postOutRequest();
  523.            
  524.            
  525.            
  526.            
  527.            
  528. //          /* ------------  PreInResponseHandler ------------- */
  529.             // Con connettore SAAJ non e' utilizzabile
  530. //          this.preInResponse();
  531. //          
  532. //          // Lettura risposta parametri NotifierInputStream per la risposta
  533. //          org.openspcoop.utils.io.notifier.NotifierInputStreamParams notifierInputStreamParams = null;
  534. //          if(this.preInResponseContext!=null){
  535. //              notifierInputStreamParams = this.preInResponseContext.getNotifierInputStreamParams();
  536. //          }
  537.            
  538.            
  539.            
  540.            
  541.             return true;
  542.         }  catch(Exception e){
  543.             this.eccezioneProcessamento = e;
  544.             String msgErrore = this.readExceptionMessageFromException(e);
  545.             if(this.generateErrorWithConnectorPrefix) {
  546.                 this.errore = "Errore avvenuto durante la consegna SOAP: "+msgErrore;
  547.             }
  548.             else {
  549.                 this.errore = msgErrore;
  550.             }
  551.             this.logger.error("Errore avvenuto durante la consegna SOAP: "+msgErrore,e);
  552.            
  553.             this.processConnectionTimeoutException(connectionTimeout, connectionTimeoutConfigurazioneGlobale, e, msgErrore);
  554.            
  555.             this.processReadTimeoutException(readConnectionTimeout, readConnectionTimeoutConfigurazioneGlobale, e, msgErrore);
  556.            
  557.             return false;
  558.         }
  559.     }

  560.     /**
  561.      * Effettua la disconnessione
  562.      */
  563.     @Override
  564.     public void disconnect() throws ConnettoreException{
  565.        
  566.         List<Throwable> listExceptionChiusura = new ArrayList<Throwable>();
  567.         try{
  568.        
  569.             if(this.connection!=null){
  570.                 if(this.debug && this.logger!=null)
  571.                     this.logger.debug("Connection.close ...");
  572.                 try {
  573.                     this.connection.close();
  574.                 }catch(Throwable t) {
  575.                     if(this.logger!=null) {
  576.                         this.logger.debug("Chiusura socket fallita: "+t.getMessage(),t);
  577.                     }
  578.                     listExceptionChiusura.add(t);
  579.                 }
  580.             }
  581.            
  582.             // super.disconnect (Per risorse base)
  583.             try {
  584.                 super.disconnect();
  585.             }catch(Throwable t) {
  586.                 if(this.logger!=null) {
  587.                     this.logger.debug("Chiusura risorse fallita: "+t.getMessage(),t);
  588.                 }
  589.                 listExceptionChiusura.add(t);
  590.             }
  591.            
  592.         }catch(Exception e){
  593.             throw new ConnettoreException("Chiusura connessione non riuscita: "+e.getMessage(),e);
  594.         }  
  595.        
  596.         if(listExceptionChiusura!=null && !listExceptionChiusura.isEmpty()) {
  597.             org.openspcoop2.utils.UtilsMultiException multiException = new org.openspcoop2.utils.UtilsMultiException(listExceptionChiusura.toArray(new Throwable[1]));
  598.             throw new ConnettoreException("Chiusura connessione non riuscita: "+multiException.getMessage(),multiException);
  599.         }
  600.     }
  601.    
  602.     private void setRequestHeader(boolean validazioneHeaderRFC2047, String key, List<String> values, ConnettoreLogger logger, Map<String, List<String>> propertiesTrasportoDebug) throws Exception {
  603.        
  604.         if(validazioneHeaderRFC2047){
  605.             try{
  606.                 RFC2047Utilities.validHeader(key, values);
  607.                 setRequestHeader(key, values, propertiesTrasportoDebug);
  608.             }catch(UtilsException e){
  609.                 logger.error(e.getMessage(),e);
  610.             }
  611.         }
  612.         else{
  613.             setRequestHeader(key,values, propertiesTrasportoDebug);
  614.         }
  615.        
  616.     }
  617.    
  618.     @Override
  619.     protected void setRequestHeader(String key,List<String> values) throws Exception {
  620.         if(values!=null && !values.isEmpty()) {
  621.             for (String value : values) {
  622.                 this.soapRequestMessage.getMimeHeaders().addHeader(key,value);  
  623.             }
  624.         }
  625.     }
  626.    
  627. }