SDIImbustamento.java

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

  21. import java.io.ByteArrayInputStream;
  22. import java.math.BigInteger;
  23. import java.util.ArrayList;
  24. import java.util.List;

  25. import javax.xml.soap.AttachmentPart;
  26. import javax.xml.soap.SOAPBody;
  27. import javax.xml.soap.SOAPElement;
  28. import javax.xml.soap.SOAPPart;

  29. import org.openspcoop2.message.OpenSPCoop2Message;
  30. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  31. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  32. import org.openspcoop2.message.constants.Costanti;
  33. import org.openspcoop2.message.soap.SoapUtils;
  34. import org.openspcoop2.message.utils.MessageUtilities;
  35. import org.openspcoop2.message.xml.MessageXMLUtils;
  36. import org.openspcoop2.protocol.sdi.config.SDIProperties;
  37. import org.openspcoop2.protocol.sdi.config.SDITraduttore;
  38. import org.openspcoop2.protocol.sdi.constants.SDICostanti;
  39. import org.openspcoop2.protocol.sdi.constants.SDICostantiServizioRiceviFile;
  40. import org.openspcoop2.protocol.sdi.constants.SDICostantiServizioRiceviNotifica;
  41. import org.openspcoop2.protocol.sdi.utils.SDICompatibilitaNamespaceErrati;
  42. import org.openspcoop2.protocol.sdi.utils.SDIFatturaUtils;
  43. import org.openspcoop2.protocol.sdi.utils.SDIUtils;
  44. import org.openspcoop2.protocol.sdi.validator.SDIValidazioneUtils;
  45. import org.openspcoop2.protocol.sdk.Busta;
  46. import org.openspcoop2.protocol.sdk.Eccezione;
  47. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  48. import org.openspcoop2.protocol.sdk.ProtocolException;
  49. import org.openspcoop2.protocol.sdk.state.IState;
  50. import org.openspcoop2.utils.Utilities;
  51. import org.openspcoop2.utils.xml.AbstractValidatoreXSD;

  52. import it.gov.fatturapa.sdi.messaggi.v1_0.constants.TipiMessaggi;

  53. /**
  54.  * SDIImbustamento
  55.  *
  56.  * @author Andrea Poli (apoli@link.it)
  57.  * @author $Author$
  58.  * @version $Rev$, $Date$
  59.  */
  60. public class SDIImbustamento {

  61.     private SDIBustaBuilder bustaBuilder = null;
  62.     private SDIValidazioneUtils sdiUtils = null;
  63.     private SDITraduttore sdiTraduttore = null;
  64.     private SDIProperties sdiProperties = null;
  65.     public SDIImbustamento(SDIBustaBuilder bustaBuilder) throws ProtocolException{
  66.         this.bustaBuilder = bustaBuilder;
  67.         this.sdiUtils = new SDIValidazioneUtils(bustaBuilder.getProtocolFactory());
  68.         this.sdiTraduttore = (SDITraduttore) bustaBuilder.getProtocolFactory().createTraduttore();
  69.         this.sdiProperties = SDIProperties.getInstance(bustaBuilder.getProtocolFactory().getLogger());
  70.     }
  71.    
  72.     public SOAPElement creaRichiesta_ServizioSdIRiceviFile_AzioneRiceviFile(IProtocolFactory<?> protocolFactory, IState state, Busta busta, OpenSPCoop2Message msgParam) throws ProtocolException{
  73.        
  74.         try{
  75.             OpenSPCoop2SoapMessage msg = msgParam.castAsSoap();
  76.             OpenSPCoop2MessageFactory messageFactory = msgParam.getFactory();
  77.             MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(messageFactory);
  78.                    
  79.             // create body
  80.             SOAPPart soapPart = msg.getSOAPPart();
  81.             SOAPBody soapBody = msg.getSOAPBody();
  82.             if(soapBody==null){
  83.                 soapBody = soapPart.getEnvelope().addBody();
  84.             }
  85.            
  86.        
  87.             // !!NOTA!! : Per comprendere cosa sia presente nel soapBody e negli attachments vedere org.openspcoop2.protocol.sdi.utils.PreInRequestHandler
  88.            
  89.            
  90.             // childElement
  91.             List<SOAPElement> childs = SoapUtils.getNotEmptyChildSOAPElement(soapBody);
  92.             if(childs==null || childs.size()<=0){
  93.                 throw new Exception("FatturaPA non presente");
  94.             }
  95.             if(childs.size()>1){
  96.                 throw new Exception("Sono presenti piu' elementi xml. Deve essere fornita una singola FatturaPA (o file ZIP)");
  97.             }
  98.             SOAPElement fatturaSOAPElement = childs.get(0);
  99.            
  100.            
  101.            
  102.             // tipoInvioFattura
  103.             String tipoInvioFattura = null;
  104.             byte[] fatturaAllegata = null;
  105.             String idPaese = null;
  106.             String idCodice = null;
  107.             String versioneFattura = null;
  108.             if(Costanti.SOAP_TUNNEL_NAMESPACE.equals(fatturaSOAPElement.getNamespaceURI())){
  109.                
  110.                 // Grazie alla classe org.openspcoop2.protocol.sdi.utils.PreInRequestHandler entreremo qua nel caso ZIP o P7M
  111.                
  112.                 // versioneFattura
  113.                 if(msg.getTransportRequestContext()!=null){
  114.                     versioneFattura =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_VERSIONE_FATTURA);
  115.                     if(versioneFattura==null){
  116.                         versioneFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_VERSIONE_FATTURA_1);
  117.                     }
  118.                     if(versioneFattura==null){
  119.                         versioneFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_VERSIONE_FATTURA_2);
  120.                     }
  121.                 }
  122.                 if(versioneFattura==null){
  123.                     throw new Exception("Versione non fornita (indicare una delle seguenti versioni: "+SDICostanti.SDI_VERSIONI_FATTURA+")");
  124.                 }
  125.                 versioneFattura = versioneFattura.trim().toUpperCase();
  126.                 if(SDICostanti.SDI_VERSIONI_FATTURA.contains(versioneFattura)==false){
  127.                     throw new Exception("Versione fornita ["+versioneFattura+"] non supportata (indicare una delle seguenti versioni: "+SDICostanti.SDI_VERSIONI_FATTURA+")");
  128.                 }
  129.                                
  130.                 // nomeFileFattura
  131.                 String tipoFileFattura = null;
  132.                 if(msg.getTransportRequestContext()!=null){
  133.                     tipoFileFattura =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_TIPO_FILE);
  134.                     if(tipoFileFattura==null){
  135.                         tipoFileFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_TIPO_FILE_1);
  136.                     }
  137.                     if(tipoFileFattura==null){
  138.                         tipoFileFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_TIPO_FILE_2);
  139.                     }
  140.                 }
  141.                 if(tipoFileFattura==null){
  142.                     //throw new Exception("TipoFileFattura non fornito");
  143.                     // Bug Fix: OP-752
  144.                     // forzo xml che gestiro' comunque come attachment
  145.                     tipoFileFattura = SDICostanti.SDI_TIPO_FATTURA_XML;
  146.                 }
  147.                 if(SDICostanti.SDI_TIPO_FATTURA_XML.equalsIgnoreCase(tipoFileFattura)){
  148.                     tipoInvioFattura = SDICostanti.SDI_TIPO_FATTURA_XML;
  149.                 }
  150.                 else if(SDICostanti.SDI_TIPO_FATTURA_ZIP.equalsIgnoreCase(tipoFileFattura)){
  151.                     tipoInvioFattura = SDICostanti.SDI_TIPO_FATTURA_ZIP;
  152.                 }
  153.                 else if(SDICostanti.SDI_TIPO_FATTURA_P7M.equalsIgnoreCase(tipoFileFattura)){
  154.                     tipoInvioFattura = SDICostanti.SDI_TIPO_FATTURA_P7M;
  155.                 }
  156.                 else{
  157.                     throw new Exception("TipoFileFattura fornito non supportato: "+tipoInvioFattura);
  158.                 }
  159.                
  160.                 // idPaese
  161.                 if(msg.getTransportRequestContext()!=null){
  162.                     idPaese =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_ID_PAESE);
  163.                     if(idPaese==null){
  164.                         idPaese =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_ID_PAESE_1);
  165.                     }
  166.                     if(idPaese==null){
  167.                         idPaese =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_ID_PAESE_2);
  168.                     }
  169.                 }
  170.                 if(idPaese==null){
  171.                     if(!SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  172.                         throw new Exception("IdPaese non fornito");
  173.                     }
  174.                 }
  175.                
  176.                 // idCodice
  177.                 if(msg.getTransportRequestContext()!=null){
  178.                     idCodice =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_ID_CODICE);
  179.                     if(idCodice==null){
  180.                         idCodice =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_ID_CODICE_1);
  181.                     }
  182.                     if(idCodice==null){
  183.                         idCodice =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_ID_CODICE_2);
  184.                     }
  185.                 }
  186.                 if(idCodice==null){
  187.                     if(!SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  188.                         throw new Exception("IdCodice non fornito");
  189.                     }
  190.                 }
  191.                
  192.                 if(msg.countAttachments()<=0){
  193.                     throw new Exception("Atteso fattura come attachment");
  194.                 }
  195.                 AttachmentPart ap = (AttachmentPart) msg.getAttachments().next();
  196.                 fatturaAllegata = Utilities.getAsByteArray(ap.getDataHandler().getInputStream());
  197.             }
  198.             else{
  199.                
  200.                 tipoInvioFattura = SDICostanti.SDI_TIPO_FATTURA_XML;
  201.                
  202.                 // versioneFattura
  203.                 if(msg.getTransportRequestContext()!=null){
  204.                     versioneFattura =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_VERSIONE_FATTURA);
  205.                     if(versioneFattura==null){
  206.                         versioneFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_VERSIONE_FATTURA_1);
  207.                     }
  208.                     if(versioneFattura==null){
  209.                         versioneFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_VERSIONE_FATTURA_2);
  210.                     }
  211.                 }
  212.                 if(versioneFattura==null){
  213.                     if(it.gov.fatturapa.sdi.fatturapa.v1_0.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  214.                         versioneFattura = SDICostanti.SDI_VERSIONE_FATTURA_PA_10;
  215.                     }
  216.                     else if(it.gov.fatturapa.sdi.fatturapa.v1_1.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  217.                         versioneFattura = SDICostanti.SDI_VERSIONE_FATTURA_PA_11;
  218.                     }
  219.                     else if(it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v1_0.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  220.                         versioneFattura = SDICostanti.SDI_VERSIONE_FATTURA_SEMPLIFICATA_10;
  221.                     }
  222.                     else{
  223.                         // non e' possibile capire la versione dal namespace, la versione 1.2 contiene due versioni interne, una per private ed una per PA
  224.                         throw new Exception("Versione non fornita (indicare una delle seguenti versioni: "+SDICostanti.SDI_VERSIONI_FATTURA+")");
  225.                     }
  226.                 }
  227.                 else{
  228.                     if(SDICostanti.SDI_VERSIONI_FATTURA.contains(versioneFattura)==false){
  229.                         throw new Exception("Versione fornita ["+versioneFattura+"] non supportata (indicare una delle seguenti versioni: "+SDICostanti.SDI_VERSIONI_FATTURA+")");
  230.                     }
  231.                     // check in accordo alla versione
  232.                     if(SDICostanti.SDI_VERSIONE_FATTURA_PA_10.equals(versioneFattura)){
  233.                         if(!it.gov.fatturapa.sdi.fatturapa.v1_0.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  234.                             throw new Exception("Versione fornita ["+versioneFattura+"] non è utilizzabile con la fattura fornita che appartiene ad una differente versione di namespace ["+fatturaSOAPElement.getNamespaceURI()+"]");
  235.                         }
  236.                     }
  237.                     else if(SDICostanti.SDI_VERSIONE_FATTURA_PA_11.equals(versioneFattura)){
  238.                         if(!it.gov.fatturapa.sdi.fatturapa.v1_1.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  239.                             throw new Exception("Versione fornita ["+versioneFattura+"] non è utilizzabile con la fattura fornita che appartiene ad una differente versione di namespace ["+fatturaSOAPElement.getNamespaceURI()+"]");
  240.                         }
  241.                     }
  242.                     else if(SDICostanti.SDI_VERSIONE_FATTURA_SEMPLIFICATA_10.equals(versioneFattura)){
  243.                         if(!it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v1_0.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  244.                             throw new Exception("Versione fornita ["+versioneFattura+"] non è utilizzabile con la fattura fornita che appartiene ad una differente versione di namespace ["+fatturaSOAPElement.getNamespaceURI()+"]");
  245.                         }
  246.                     }
  247.                     else{
  248.                         if(!it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v1_2.utils.ProjectInfo.getInstance().getProjectNamespace().equals(fatturaSOAPElement.getNamespaceURI())){
  249.                             throw new Exception("Versione fornita ["+versioneFattura+"] non è utilizzabile con la fattura fornita che appartiene ad una differente versione di namespace ["+fatturaSOAPElement.getNamespaceURI()+"]");
  250.                         }
  251.                     }
  252.                 }
  253.                
  254.             }
  255.            
  256.             // NomeFileFattura da spedire
  257.             String nomeFileFatturaDaSpedire = null;
  258.             boolean readNomeFromTrasporto = false;
  259.             if( (!this.sdiProperties.isEnable_fatturazioneAttiva_generazioneNomeFileFattura()) || this.sdiProperties.isEnable_fatturazioneAttiva_generazioneNomeFileFatturaOpzionale()) {
  260.                 readNomeFromTrasporto = true;
  261.             }
  262.             if(readNomeFromTrasporto) {
  263.                 if(msg.getTransportRequestContext()!=null){
  264.                     nomeFileFatturaDaSpedire =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_URLBASED_NOME_FILE);
  265.                     if(nomeFileFatturaDaSpedire==null){
  266.                         nomeFileFatturaDaSpedire =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_NOME_FILE_1);
  267.                     }
  268.                     if(nomeFileFatturaDaSpedire==null){
  269.                         nomeFileFatturaDaSpedire =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviFile.RICEVI_FILE_INTEGRAZIONE_TRASPORTO_NOME_FILE_2);
  270.                     }
  271.                 }
  272.                 if(nomeFileFatturaDaSpedire==null && (!this.sdiProperties.isEnable_fatturazioneAttiva_generazioneNomeFileFattura()) ){
  273.                     throw new Exception("Nome file fattura non fornito");
  274.                 }
  275.             }
  276.            
  277.            
  278.             // Add Property in Busta
  279.             busta.addProperty(SDICostanti.SDI_BUSTA_EXT_FORMATO_ARCHIVIO_INVIO_FATTURA, tipoInvioFattura);
  280.             busta.addProperty(SDICostanti.SDI_BUSTA_EXT_VERSIONE_FATTURA_PA, versioneFattura);
  281.            

  282.            
  283.             // Leggo Fattura
  284.             byte[]fatturaBytes = fatturaAllegata;
  285.             if(fatturaBytes==null && SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  286.                 try{
  287.                     fatturaBytes = xmlUtils.toByteArray(fatturaSOAPElement);
  288.                 }catch(Exception e){
  289.                     throw new Exception("Fattura non valida: "+e.getMessage(),e);
  290.                 }
  291.             }
  292.            
  293.            
  294.            
  295.             // effettuo validazione del messaggio ricevuto
  296.             if(this.sdiProperties.isEnableValidazioneXsdFatturaDaInviare()){
  297.                 AbstractValidatoreXSD validatore = null;
  298.                 try{            
  299.                     if(SDICostanti.SDI_VERSIONE_FATTURA_PA_10.equals(versioneFattura)){
  300.                         validatore = it.gov.fatturapa.sdi.fatturapa.v1_0.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  301.                     }
  302.                     else if(SDICostanti.SDI_VERSIONE_FATTURA_PA_11.equals(versioneFattura)){
  303.                         validatore = it.gov.fatturapa.sdi.fatturapa.v1_1.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  304.                     }
  305.                     else if(SDICostanti.SDI_VERSIONE_FATTURA_SEMPLIFICATA_10.equals(versioneFattura)){
  306.                         validatore = it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v1_0.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  307.                     }
  308.                     else{
  309.                         validatore = it.gov.agenziaentrate.ivaservizi.docs.xsd.fatture.v1_2.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  310.                     }
  311.                 }catch(Exception e){
  312.                     throw new Exception("Inizializzazione schema per validazione fattura non riuscita: "+e.getMessage(),e);
  313.                 }
  314.                 if(SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  315.                     try{
  316.                         // Fix Validazione versione
  317.                         // axiom non funziona
  318.     //                  Attr attr = fatturaSOAPElement.getAttributeNode("versione");
  319.     //                  if(attr!=null){
  320.     //                      fatturaSOAPElement.removeAttributeNode(attr);
  321.     //                      Node nAttr = soapPart.createAttributeNS(null, "versione");
  322.     //                      nAttr.setNodeValue(attr.getNodeValue());
  323.     //                      if(fatturaSOAPElement.getAttributes()!=null){
  324.     //                          fatturaSOAPElement.getAttributes().setNamedItem(nAttr);
  325.     //                      }
  326.     //                  }
  327.     //                  validatore.valida(fatturaSOAPElement);
  328.                        
  329.                         validatore.valida(new ByteArrayInputStream(fatturaBytes));
  330.                        
  331.                     }catch(Exception e){
  332.                         throw new Exception("Fattura non valida: "+e.getMessage(),e);
  333.                     }
  334.                 }else{
  335.                     // TODO: capirlo aprendo lo zip o ignorarlo per p7m
  336.                 }
  337.             }
  338.            
  339.            
  340.             // Leggo Fattura
  341.             if(SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  342.                 try{
  343.                     List<Eccezione> erroriValidazione = new ArrayList<>();
  344.                     boolean forceDisableValidazioneXsd = true; // la validazione se abilitata e' stata fatta prima
  345.                     SDIFatturaUtils.validazioneFattura(fatturaBytes,this.sdiProperties,
  346.                             erroriValidazione,
  347.                             this.sdiUtils,protocolFactory,
  348.                             busta,msg,false,false,forceDisableValidazioneXsd);
  349.                     if(erroriValidazione!=null && erroriValidazione.size()>0){
  350.                         StringBuilder bf = new StringBuilder();
  351.                         for(int k=0; k<erroriValidazione.size();k++){
  352.                             Eccezione error = erroriValidazione.get(k);
  353.                             try{
  354.                                 bf.append("Processamento["+this.sdiTraduttore.toString(error.getCodiceEccezione(),error.getSubCodiceEccezione())+
  355.                                         "] "+error.getDescrizione(protocolFactory)+"\n");
  356.                             }catch(Exception e){
  357.                                 protocolFactory.getLogger().error("getDescrizione Error:"+e.getMessage(),e);
  358.                             }
  359.                         }
  360.                         throw new Exception(bf.toString());
  361.                     }
  362.                 }catch(Exception e){
  363.                     throw new Exception("Fattura non valida: "+e.getMessage(),e);
  364.                 }
  365.             }else{
  366.                 // TODO: capirlo aprendo lo zip o ignorarlo per p7m
  367.             }
  368.            
  369.            
  370.             // Costruisco Messaggio Protocollo
  371.             it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.ObjectFactory of = new it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.ObjectFactory();
  372.             it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.FileSdIBaseType fileSdi = new it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.FileSdIBaseType();
  373.             fileSdi.setFile(fatturaBytes);
  374.             if(nomeFileFatturaDaSpedire==null && this.sdiProperties.isEnable_fatturazioneAttiva_generazioneNomeFileFattura()) {
  375.                 if(SDICostanti.SDI_TIPO_FATTURA_XML.equals(tipoInvioFattura)){
  376.                     fileSdi.setNomeFile(SDIUtils.getNomeFileFattura(protocolFactory, state,
  377.                             idPaese!=null ? idPaese : busta.getProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_PAESE),
  378.                             idCodice!=null ? idCodice : busta.getProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_CODICE),
  379.                             tipoInvioFattura));
  380.                 }else{
  381.                     fileSdi.setNomeFile(SDIUtils.getNomeFileFattura(protocolFactory, state,
  382.                             idPaese,
  383.                             idCodice,
  384.                             tipoInvioFattura));
  385.                 }
  386.             }
  387.             else {
  388.                 if(nomeFileFatturaDaSpedire==null) {
  389.                     throw new Exception("Nome file fattura non fornito");
  390.                 }
  391.                 fileSdi.setNomeFile(nomeFileFatturaDaSpedire);
  392.             }
  393.             if(idPaese!=null && !"".equals(idPaese)) {
  394.                 if(!busta.existsProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_PAESE)) {
  395.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_PAESE, idPaese);
  396.                 }
  397.             }
  398.             if(idCodice!=null && !"".equals(idCodice)) {
  399.                 if(!busta.existsProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_CODICE)) {
  400.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_TRASMITTENTE_ID_CODICE, idCodice);
  401.                 }
  402.             }
  403.            
  404.             // detach body
  405.             soapBody.removeContents();
  406.            
  407.             // se sono presenti degli attachments li elimino
  408.             if(msg.countAttachments()>0){
  409.                 msg.removeAllAttachments();
  410.             }
  411.            
  412.             // add MessaggioProtocollo
  413.             it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.utils.serializer.JaxbSerializer serializer = new it.gov.fatturapa.sdi.ws.trasmissione.v1_0.types.utils.serializer.JaxbSerializer();
  414.             String xmlRichiesta = serializer.toString(of.createFileSdIAccoglienza(fileSdi));
  415.             SOAPElement element = SoapUtils.getSoapFactory(messageFactory, msg.getMessageType()).createElement(xmlUtils.newElement(xmlRichiesta.getBytes()));
  416.             soapBody.addChildElement(element);
  417.            
  418.             // salvo nomeFile
  419.             busta.addProperty(SDICostanti.SDI_BUSTA_EXT_NOME_FILE, fileSdi.getNomeFile());
  420.            
  421.             // soapAction
  422.             msg.setSoapAction(SDICostantiServizioRiceviFile.SDI_SOAP_ACTION_SERVIZIO_RICEVI_FILE_AZIONE_RICEVI_FILE);
  423.            
  424.             return SDIUtils.readHeader(msg); // l'header ritornato viene usato solo per il tracciamento e cosi' facendo viene ripulito
  425.            
  426.         }catch(Exception e){
  427.             throw new ProtocolException(e.getMessage(),e);
  428.         }
  429.        
  430.     }
  431.    
  432.     public SOAPElement creaRisposta_ServizioRicezioneFatture_AzioneRiceviFatture(IProtocolFactory<?> protocolFactory, IState state, Busta busta, OpenSPCoop2Message msgParam) throws ProtocolException{
  433.        
  434.         try{
  435.             OpenSPCoop2SoapMessage msg = msgParam.castAsSoap();
  436.             OpenSPCoop2MessageFactory messageFactory = msgParam.getFactory();
  437.             MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(messageFactory);
  438.            
  439.             // create body
  440.             SOAPPart soapPart = msg.getSOAPPart();
  441.             SOAPBody soapBody = msg.getSOAPBody();
  442.             if(soapBody==null){
  443.                 soapBody = soapPart.getEnvelope().addBody();
  444.             }
  445.             else{
  446.                 if(soapBody.hasFault()){
  447.                     return null; // vi e' stato un errore in fase di consegna
  448.                 }
  449.             }
  450.            
  451.             // detach body
  452.             soapBody.removeContents();
  453.            
  454.             // se sono presenti degli attachments li elimino
  455.             if(msg.countAttachments()>0){
  456.                 msg.removeAllAttachments();
  457.             }
  458.            
  459.             // imposto content type
  460.             msg.setContentType(MessageUtilities.getDefaultContentType(msg.getMessageType()));
  461.            
  462.             // add MessaggioProtocollo
  463.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.ObjectFactory of = new it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.ObjectFactory();
  464.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.RispostaRiceviFattureType rispostaRiceviFatture = of.createRispostaRiceviFattureType();
  465.             rispostaRiceviFatture.setEsito(it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.constants.EsitoRicezioneType.ER01);
  466.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.utils.serializer.JaxbSerializer serializer = new it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.utils.serializer.JaxbSerializer();
  467.             String xmlRisposta = serializer.toString(of.createRispostaRiceviFatture(rispostaRiceviFatture));
  468.             SOAPElement element = SoapUtils.getSoapFactory(messageFactory, msg.getMessageType()).createElement(xmlUtils.newElement(xmlRisposta.getBytes()));
  469.             soapBody.addChildElement(element);
  470.            
  471.             return element; // non vi sono base64
  472.                        
  473.         }catch(Exception e){
  474.             throw new ProtocolException(e.getMessage(),e);
  475.         }
  476.        
  477.     }
  478.    
  479.     public SOAPElement creaRichiesta_ServizioSdIRiceviNotifica_AzioneNotificaEsito(IProtocolFactory<?> protocolFactory, IState state, Busta busta, OpenSPCoop2Message msgParam,
  480.             boolean isEnableGenerazioneMessaggiCompatibilitaNamespaceSenzaGov,
  481.             boolean isEnableValidazioneMessaggiCompatibilitaNamespaceSenzaGov) throws ProtocolException{
  482.        
  483.         try{
  484.             OpenSPCoop2SoapMessage msg = msgParam.castAsSoap();
  485.             OpenSPCoop2MessageFactory messageFactory = msgParam.getFactory();
  486.             MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(messageFactory);
  487.        
  488.             // create body
  489.             SOAPPart soapPart = msg.getSOAPPart();
  490.             SOAPBody soapBody = msg.getSOAPBody();
  491.             if(soapBody==null){
  492.                 soapBody = soapPart.getEnvelope().addBody();
  493.             }
  494.            
  495.             // nomeFileFattura
  496.             String nomeFileFattura = null;
  497.             if(msg.getTransportRequestContext()!=null){
  498.                 nomeFileFattura =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_URLBASED_NOME_FILE);
  499.                 if(nomeFileFattura==null){
  500.                     nomeFileFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_TRASPORTO_NOME_FILE_1);
  501.                 }
  502.                 if(nomeFileFattura==null){
  503.                     nomeFileFattura =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_TRASPORTO_NOME_FILE_2);
  504.                 }
  505.             }
  506.             if(nomeFileFattura==null){
  507.                 if(this.sdiProperties.isEnable_fatturazionePassiva_generazioneNomeFileEsito()) {
  508.                     throw new Exception("Nome File Fattura non fornito");
  509.                 }
  510.                 else {
  511.                     throw new Exception("Nome File Esito non fornito");
  512.                 }
  513.             }
  514.            
  515.             // identificativoSdi
  516.             String identificativoSdi = null;
  517.             String tmpIdentificativoSdi = null;
  518.             if(msg.getTransportRequestContext()!=null){
  519.                 tmpIdentificativoSdi =  msg.getTransportRequestContext().getParameterFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_URLBASED_IDENTIFICATIVO_SDI);
  520.                 if(tmpIdentificativoSdi==null){
  521.                     tmpIdentificativoSdi =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_TRASPORTO_IDENTIFICATIVO_SDI_1);
  522.                 }
  523.                 if(tmpIdentificativoSdi==null){
  524.                     tmpIdentificativoSdi =  msg.getTransportRequestContext().getHeaderFirstValue(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_INTEGRAZIONE_TRASPORTO_IDENTIFICATIVO_SDI_2);
  525.                 }
  526.             }
  527.             boolean accessoNotificaDaInviare = this.sdiProperties.isEnableAccessoNotificaDaInviare();
  528.             if(tmpIdentificativoSdi==null && !accessoNotificaDaInviare){
  529.                 throw new Exception("IdentificativoSdi non fornito");
  530.             }
  531.             if(tmpIdentificativoSdi!=null) {
  532.                 try {
  533.                     if(this.sdiProperties.isEnable_InputIdSDIValidationAsBigInteger_NotificaDaInviare()) {
  534.                         BigInteger bigInteger = new BigInteger(tmpIdentificativoSdi);
  535.                         String s = bigInteger.toString();
  536.                         if(s!=null) {
  537.                             // validazione superata
  538.                         }
  539.                     }
  540.                     identificativoSdi = tmpIdentificativoSdi;
  541.                 }catch(Exception e) {
  542.                     throw new Exception("IdentificativoSdi fornito non possiede un valore valido: "+e.getMessage());
  543.                 }
  544.             }
  545.            
  546.             // childElement
  547.             List<SOAPElement> childs = SoapUtils.getNotEmptyChildSOAPElement(soapBody);
  548.             if(childs==null || childs.size()<=0){
  549.                 throw new Exception("Notifica di Esito Committente non presente");
  550.             }
  551.             if(childs.size()>1){
  552.                 throw new Exception("Sono presenti piu' elementi xml. Deve essere fornita una singola Notifica di Esito Committente");
  553.             }
  554.             SOAPElement notificaEsitoCommittenteSOAPElement = childs.get(0);
  555.            
  556.             byte[]notificaEsitoCommittenteBytes = null;
  557.             if(Costanti.SOAP_TUNNEL_NAMESPACE.equals(notificaEsitoCommittenteSOAPElement.getNamespaceURI())){
  558.                 if(msg.countAttachments()<=0){
  559.                     throw new Exception("Attesa notifica come attachment");
  560.                 }
  561.                 AttachmentPart ap = (AttachmentPart) msg.getAttachments().next();
  562.                 notificaEsitoCommittenteBytes = Utilities.getAsByteArray(ap.getDataHandler().getInputStream());
  563.             }
  564.             else {
  565.                 notificaEsitoCommittenteBytes = xmlUtils.toByteArray(notificaEsitoCommittenteSOAPElement);
  566.             }
  567.             // effettuo validazione del messaggio ricevuto
  568.             byte [] notificaEsitoCommittenteBytesCompatibilitaSenzaGov = notificaEsitoCommittenteBytes;
  569.             try{
  570.                 // Fix Validazione versione
  571. //              Attr attr = notificaEsitoCommittenteSOAPElement.getAttributeNode("versione");
  572. //              if(attr!=null){
  573. //                  notificaEsitoCommittenteSOAPElement.removeAttributeNode(attr);
  574. //                  Node nAttr = soapPart.createAttributeNS(null, "versione");
  575. //                  nAttr.setNodeValue(attr.getNodeValue());
  576. //                  if(notificaEsitoCommittenteSOAPElement.getAttributes()!=null){
  577. //                      notificaEsitoCommittenteSOAPElement.getAttributes().setNamedItem(nAttr);
  578. //                  }
  579. //              }              
  580. //              AbstractValidatoreXSD validatore = it.gov.fatturapa.sdi.messaggi.v1_0.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  581. //              validatore.valida(notificaEsitoCommittenteSOAPElement);
  582.                
  583.                 // effettuo validazione con bytes, per ovviare al problema del namespace 'gov'
  584.                 if(isEnableValidazioneMessaggiCompatibilitaNamespaceSenzaGov){
  585.                     notificaEsitoCommittenteBytesCompatibilitaSenzaGov = SDICompatibilitaNamespaceErrati.convertiXmlNamespaceSenzaGov(protocolFactory.getLogger(), notificaEsitoCommittenteBytes);
  586.                 }
  587.                
  588.                 // validazione
  589.                 if(this.sdiProperties.isEnableValidazioneXsdNotificaDaInviare()){
  590.                     AbstractValidatoreXSD validatore = it.gov.fatturapa.sdi.messaggi.v1_0.utils.XSDValidatorWithSignature.getOpenSPCoop2MessageXSDValidator(this.bustaBuilder.getProtocolFactory().getLogger());
  591.                     validatore.valida(new ByteArrayInputStream(notificaEsitoCommittenteBytesCompatibilitaSenzaGov));
  592.                 }
  593.                
  594.             }catch(Exception e){
  595.                 throw new Exception("Notifica di Esito Committente non valida: "+e.getMessage(),e);
  596.             }
  597.            
  598.             // Leggo NotificaEsitoCommittente
  599.             it.gov.fatturapa.sdi.messaggi.v1_0.NotificaEsitoCommittenteType notificaEsitoCommittente = null;
  600.             if(accessoNotificaDaInviare) {
  601.                 try{
  602.                     // fatto prima in validazion: notificaEsitoCommittenteBytes = this.xmlUtils.toByteArray(notificaEsitoCommittenteSOAPElement);
  603.                     it.gov.fatturapa.sdi.messaggi.v1_0.utils.serializer.JaxbDeserializer deserializer = new
  604.                             it.gov.fatturapa.sdi.messaggi.v1_0.utils.serializer.JaxbDeserializer();
  605.                     notificaEsitoCommittente = deserializer.readNotificaEsitoCommittenteType(notificaEsitoCommittenteBytesCompatibilitaSenzaGov);
  606.                 }catch(Exception e){
  607.                     throw new Exception("Notifica di Esito Committente non valida: "+e.getMessage(),e);
  608.                 }
  609.            
  610.            
  611.                 // Aggiunto info alla busta
  612.                
  613.                 // Esito.IdentificativoSdI
  614.                 if(notificaEsitoCommittente.getIdentificativoSdI()!=null){
  615.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_IDENTIFICATIVO_SDI, notificaEsitoCommittente.getIdentificativoSdI().toString());
  616.                     identificativoSdi = notificaEsitoCommittente.getIdentificativoSdI();
  617.                 }          
  618.                 // Esito.RiferimentoFattura
  619.                 if(notificaEsitoCommittente.getRiferimentoFattura()!=null){
  620.                     if(notificaEsitoCommittente.getRiferimentoFattura().getAnnoFattura()!=null){
  621.                         busta.addProperty(SDICostanti.SDI_BUSTA_EXT_RIFERIMENTO_FATTURA_ANNO, notificaEsitoCommittente.getRiferimentoFattura().getAnnoFattura().toString());
  622.                     }
  623.                     if(notificaEsitoCommittente.getRiferimentoFattura().getNumeroFattura()!=null){
  624.                         busta.addProperty(SDICostanti.SDI_BUSTA_EXT_RIFERIMENTO_FATTURA_NUMERO, notificaEsitoCommittente.getRiferimentoFattura().getNumeroFattura());
  625.                     }
  626.                     if(notificaEsitoCommittente.getRiferimentoFattura().getPosizioneFattura()!=null){
  627.                         busta.addProperty(SDICostanti.SDI_BUSTA_EXT_RIFERIMENTO_FATTURA_POSIZIONE, notificaEsitoCommittente.getRiferimentoFattura().getPosizioneFattura().toString());
  628.                     }
  629.                 }          
  630.                 // Esito.Esito
  631.                 if(notificaEsitoCommittente.getEsito()!=null){
  632.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_ESITO, notificaEsitoCommittente.getEsito().name());
  633.                 }              
  634.                 // Esito.Descrizione
  635.                 if(notificaEsitoCommittente.getDescrizione()!=null){
  636.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_DESCRIZIONE, notificaEsitoCommittente.getDescrizione());
  637.                 }  
  638.                 // Esito.MessageId
  639.                 if(notificaEsitoCommittente.getMessageIdCommittente()!=null){
  640.                     busta.addProperty(SDICostanti.SDI_BUSTA_EXT_MESSAGE_ID_COMMITTENTE, notificaEsitoCommittente.getMessageIdCommittente());
  641.                 }
  642.                
  643.                 if(identificativoSdi==null){
  644.                     throw new Exception("IdentificativoSdi non fornito nella notifica da inviare");
  645.                 }
  646.             }
  647.                    
  648.            
  649.             // Costruisco Messaggio Protocollo
  650.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.ObjectFactory of = new it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.ObjectFactory();
  651.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.FileSdIType fileSdi = new it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.FileSdIType();
  652.             byte [] fileSent = notificaEsitoCommittenteBytes;
  653.             if(isEnableGenerazioneMessaggiCompatibilitaNamespaceSenzaGov){
  654.                 fileSent = SDICompatibilitaNamespaceErrati.produciXmlNamespaceSenzaGov(protocolFactory.getLogger(), fileSent);
  655.             }
  656.             fileSdi.setFile(fileSent);
  657.             fileSdi.setIdentificativoSdI(identificativoSdi);
  658.             if(this.sdiProperties.isEnable_fatturazionePassiva_generazioneNomeFileEsito()) {
  659.                 // Se è abilitata la genereazione del nome dell'esito su GovWay, il client DEVE fornire il nome della fattura originale su cui manda l'esito
  660.                 busta.addProperty(SDICostanti.SDI_BUSTA_EXT_NOME_FILE_FATTURA, nomeFileFattura);
  661.                 fileSdi.setNomeFile(SDIUtils.getNomeFileMessaggi(protocolFactory, state, nomeFileFattura, TipiMessaggi.EC));
  662.             }
  663.             else {
  664.                 // Se non è abilitata la genereazione del nome dell'esito su GovWay, il client DEVE fornire il nome del file corrispondente all'esito.
  665.                 fileSdi.setNomeFile(nomeFileFattura);
  666.             }
  667.            
  668.             // salvo informazioni
  669.             busta.addProperty(SDICostanti.SDI_BUSTA_EXT_IDENTIFICATIVO_SDI, identificativoSdi+"");
  670.             busta.addProperty(SDICostanti.SDI_BUSTA_EXT_NOME_FILE, fileSdi.getNomeFile());
  671.            
  672.             // detach body
  673.             soapBody.removeContents();
  674.            
  675.             // se sono presenti degli attachments li elimino
  676.             if(msg.countAttachments()>0){
  677.                 msg.removeAllAttachments();
  678.             }
  679.            
  680.             // add MessaggioProtocollo
  681.             it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.utils.serializer.JaxbSerializer serializer = new it.gov.fatturapa.sdi.ws.ricezione.v1_0.types.utils.serializer.JaxbSerializer();
  682.             String xmlRichiesta = serializer.toString(of.createFileSdI(fileSdi));
  683.             SOAPElement element = SoapUtils.getSoapFactory(messageFactory, msg.getMessageType()).createElement(xmlUtils.newElement(xmlRichiesta.getBytes()));
  684.             soapBody.addChildElement(element);
  685.            
  686.             // soapAction
  687.             msg.setSoapAction(SDICostantiServizioRiceviNotifica.SDI_SOAP_ACTION_SERVIZIO_NOTIFICA_ESITO_AZIONE_NOTIFICA_ESITO);
  688.                
  689.             return SDIUtils.readHeader(msg); // l'header ritornato viene usato solo per il tracciamento e cosi' facendo viene ripulito
  690.            
  691.         }catch(Exception e){
  692.             throw new ProtocolException(e.getMessage(),e);
  693.         }
  694.        
  695.     }
  696. }