SDIUtils.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.utils;

  21. import java.util.ArrayList;
  22. import java.util.List;

  23. import javax.xml.soap.SOAPBody;
  24. import javax.xml.soap.SOAPElement;

  25. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  26. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  27. import org.openspcoop2.message.soap.SoapUtils;
  28. import org.openspcoop2.message.soap.mtom.MtomXomReference;
  29. import org.openspcoop2.protocol.sdi.constants.SDICostanti;
  30. import org.openspcoop2.protocol.sdi.constants.SDICostantiServizioRiceviNotifica;
  31. import org.openspcoop2.protocol.sdi.constants.SDICostantiServizioRicezioneFatture;
  32. import org.openspcoop2.protocol.sdi.constants.SDICostantiServizioTrasmissioneFatture;
  33. import org.openspcoop2.protocol.sdi.validator.SDIValidatoreNomeFile;
  34. import org.openspcoop2.protocol.sdk.ConfigurazionePdD;
  35. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  36. import org.openspcoop2.protocol.sdk.ProtocolException;
  37. import org.openspcoop2.protocol.sdk.state.IState;
  38. import org.openspcoop2.protocol.utils.IDSerialGenerator;
  39. import org.openspcoop2.utils.id.serial.IDSerialGeneratorParameter;
  40. import org.openspcoop2.utils.id.serial.IDSerialGeneratorType;
  41. import org.openspcoop2.utils.xml.AbstractXMLUtils;
  42. import org.openspcoop2.utils.xml.DynamicNamespaceContext;
  43. import org.openspcoop2.utils.xml.XMLUtils;
  44. import org.openspcoop2.utils.xml.XPathExpressionEngine;
  45. import org.openspcoop2.utils.xml.XPathNotFoundException;
  46. import org.openspcoop2.utils.xml.XPathReturnType;
  47. import org.w3c.dom.Element;
  48. import org.w3c.dom.Node;
  49. import org.w3c.dom.NodeList;

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

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

  59.     public static SOAPElement readHeader(OpenSPCoop2SoapMessage msg) throws ProtocolException{

  60.         List<MtomXomReference> xomReference = null;
  61.         try{
  62.             OpenSPCoop2MessageFactory messageFactory = msg.getFactory();
  63.             SOAPBody soapBody = msg.getSOAPBody();
  64.             if(soapBody==null || soapBody.hasChildNodes()==false){
  65.                 return null;
  66.             }
  67.             if(soapBody.hasFault()){
  68.                 return null;
  69.             }
  70.             Element element = SoapUtils.getNotEmptyFirstChildSOAPElement(soapBody);
  71.            
  72.             // Il codice sottostante imposta un valore 'ContenutoBase64' al posto del vero contenuto Base64

  73.             // **** Servizio 'RicezioneFatture', operazione 'RiceviFatture' ******
  74.             if(SDICostantiServizioRicezioneFatture.RICEVI_FATTURE_RICHIESTA_ROOT_ELEMENT.equals(element.getLocalName()) &&
  75.                     SDICostantiServizioRicezioneFatture.RICEZIONE_SERVIZIO_RICEZIONE_FATTURE_NAMESPACE.equals(element.getNamespaceURI())){
  76.            
  77.                 xomReference = msg.mtomFastUnpackagingForXSDConformance();
  78.                 element = (Element)element.cloneNode(true);
  79.                
  80.                 List<Node> childs = SoapUtils.getNotEmptyChildNodes(messageFactory, element, false);
  81.                 for (int i = 0; i < childs.size(); i++) {
  82.                     Node child = childs.get(i);
  83.                     if(SDICostantiServizioRicezioneFatture.RICEVI_FATTURE_RICHIESTA_ELEMENT_FILE.equals(child.getLocalName())){
  84.                         child.setTextContent("ContenutoBase64");
  85.                     }
  86.                     else if(SDICostantiServizioRicezioneFatture.RICEVI_FATTURE_RICHIESTA_ELEMENT_METADATI.equals(child.getLocalName())){
  87.                         child.setTextContent("ContenutoBase64");
  88.                     }
  89.                 }
  90.             }
  91.            
  92.             // **** Servizio 'RicezioneFatture', operazione 'NotificaDecorrenzaTermini' ******
  93.             else if(SDICostantiServizioRicezioneFatture.NOTIFICA_DECORRENZA_TERMINI_RICHIESTA_ROOT_ELEMENT.equals(element.getLocalName()) &&
  94.                     SDICostantiServizioRicezioneFatture.RICEZIONE_SERVIZIO_RICEZIONE_FATTURE_NAMESPACE.equals(element.getNamespaceURI())){
  95.            
  96.                 xomReference = msg.mtomFastUnpackagingForXSDConformance();
  97.                 element = (Element)element.cloneNode(true);
  98.                
  99.                 List<Node> childs = SoapUtils.getNotEmptyChildNodes(messageFactory, element, false);
  100.                 for (int i = 0; i < childs.size(); i++) {
  101.                     Node child = childs.get(i);
  102.                     if(SDICostantiServizioRicezioneFatture.FILE_SDI_TYPE_CONSEGNA_RICHIESTA_ELEMENT_FILE.equals(child.getLocalName())){
  103.                         child.setTextContent("ContenutoBase64");
  104.                     }
  105.                 }
  106.             }
  107.            
  108.            
  109.             // **** Servizio 'RiceviNotifica', operazione 'NotificaEsito', !!richiesta!! ******
  110.             else if(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_RICHIESTA_ROOT_ELEMENT.equals(element.getLocalName()) &&
  111.                     SDICostantiServizioRiceviNotifica.SDI_SERVIZIO_RICEVI_NOTIFICA_NAMESPACE.equals(element.getNamespaceURI())){
  112.            
  113.                 xomReference = msg.mtomFastUnpackagingForXSDConformance();
  114.                 element = (Element)element.cloneNode(true);
  115.                
  116.                 List<Node> childs = SoapUtils.getNotEmptyChildNodes(messageFactory, element, false);
  117.                 for (int i = 0; i < childs.size(); i++) {
  118.                     Node child = childs.get(i);
  119.                     if(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_RICHIESTA_ELEMENT_FILE.equals(child.getLocalName())){
  120.                         child.setTextContent("ContenutoBase64");
  121.                     }
  122.                 }
  123.             }
  124.             // **** Servizio 'RiceviNotifica', operazione 'NotificaEsito', !!risposta!! (se presento lo scarto dell'esito) ******
  125.             else if(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_RISPOSTA_ROOT_ELEMENT.equals(element.getLocalName()) &&
  126.                     SDICostantiServizioRiceviNotifica.SDI_SERVIZIO_RICEVI_NOTIFICA_NAMESPACE.equals(element.getNamespaceURI())){
  127.            
  128.                 xomReference = msg.mtomFastUnpackagingForXSDConformance();
  129.                 element = (Element)element.cloneNode(true);
  130.                
  131.                 List<Node> childs = SoapUtils.getNotEmptyChildNodes(messageFactory, element, false);
  132.                 for (int i = 0; i < childs.size(); i++) {
  133.                     Node child = childs.get(i);
  134.                     if(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_RISPOSTA_ELEMENT_SCARTO_ESITO.equals(child.getLocalName())){
  135.                         List<Node> childsScarto = SoapUtils.getNotEmptyChildNodes(messageFactory, child, false);
  136.                         for (int j = 0; j < childsScarto.size(); j++) {
  137.                             Node childScarto = childsScarto.get(j);
  138.                             if(SDICostantiServizioRiceviNotifica.NOTIFICA_ESITO_RISPOSTA_ELEMENT_SCARTO_ESITO_FILE.equals(childScarto.getLocalName())){
  139.                                 childScarto.setTextContent("ContenutoBase64");
  140.                             }
  141.                         }
  142.                     }
  143.                 }
  144.             }
  145.            
  146.             // ****
  147.             //  Servizio 'TrasmissioneFatture', operazione '*' (tutte e 6)
  148.             //  Servizio 'RiceviFile', operazione 'RiceviFile'  (Possiedono lo stesso namespace e la stessa struttura)
  149.             // ******
  150.             else if(SDICostantiServizioTrasmissioneFatture.TRASMISSIONE_SERVIZIO_TRASMISSIONE_FATTURE_NAMESPACE.equals(element.getNamespaceURI())){
  151.            
  152.                 xomReference = msg.mtomFastUnpackagingForXSDConformance();
  153.                 element = (Element)element.cloneNode(true);
  154.                
  155.                 List<Node> childs = SoapUtils.getNotEmptyChildNodes(messageFactory, element, false);
  156.                 for (int i = 0; i < childs.size(); i++) {
  157.                     Node child = childs.get(i);
  158.                     if(SDICostantiServizioTrasmissioneFatture.FILE_SDI_TYPE_CONSEGNA_RICHIESTA_ELEMENT_FILE.equals(child.getLocalName())){
  159.                         child.setTextContent("ContenutoBase64");
  160.                     }
  161.                 }
  162.             }
  163.            
  164.             SOAPElement se = SoapUtils.getSoapFactory(messageFactory, msg.getMessageType()).createElement(element);
  165.            
  166.             try{
  167.                 msg.mtomRestoreAfterXSDConformance(xomReference);
  168.             }catch(Exception e){
  169.                 throw new ProtocolException(e.getMessage(),e);
  170.             }
  171.            
  172.             return se;
  173.         }catch(Exception e){
  174.             throw new ProtocolException(e.getMessage(),e);
  175.         }
  176.     }

  177.    
  178.     public static String getNomeFileMessaggi(IProtocolFactory<?> factory, IState state, String nomeFileFattura,TipiMessaggi tipo) throws ProtocolException{
  179.         // <NomeFilaFatturaRicevutoSenzaEstensione>_<TipoMessaggio>_<ProgressivoUnivoco>
  180.        
  181.         // Progressivo fileName: è relativo al file inviato
  182.         // *  - Il Progressivo univoco deve essere una stringa alfanumerica di lunghezza massima 3 caratteri e
  183.         // *  con valori ammessi [a-z], [A-Z], [0-9] che identifica univocamente ogni notifica / ricevuta relativa al file inviato.
  184.        
  185.         ConfigurazionePdD config = factory.getConfigurazionePdD();
  186.        
  187.         IDSerialGenerator serialGenerator = new IDSerialGenerator(config.getLog(), state, config.getTipoDatabase());
  188.        
  189.         IDSerialGeneratorParameter serialGeneratorParameter = new IDSerialGeneratorParameter(factory.getProtocol());
  190.         serialGeneratorParameter.setSerializableTimeWaitMs(config.getAttesaAttivaJDBC());
  191.         serialGeneratorParameter.setSerializableNextIntervalTimeMs(config.getCheckIntervalJDBC());
  192.         serialGeneratorParameter.setTipo(IDSerialGeneratorType.ALFANUMERICO);
  193.         serialGeneratorParameter.setWrap(false);
  194.         serialGeneratorParameter.setSize(3);
  195.         serialGeneratorParameter.setInformazioneAssociataAlProgressivo(SDIValidatoreNomeFile.getNomeFileFatturaSenzaEstensione(nomeFileFattura));
  196.        
  197.         String ext = "."+SDICostanti.SDI_FATTURA_ESTENSIONE_XML;
  198.        
  199.         return SDIValidatoreNomeFile.getNomeFileFatturaPerMessaggi(nomeFileFattura)+"_"+tipo.name()+"_"+serialGenerator.buildID(serialGeneratorParameter)+ext;
  200.     }
  201.    
  202.     public static String getNomeFileFattura(IProtocolFactory<?> factory, IState state, String idPaeseTrasmittente, String idCodiceTrasmittente, String formatoInvio) throws ProtocolException{
  203.        
  204.         // <codice Paese>< identificativo univoco del soggetto trasmittente >_<progressivoUnicoFile>
  205.        
  206.         // *  Progressivo fileName: è relativo al trasmittente
  207.         // *  - il progressivo univoco del file è rappresentato da una stringa alfanumerica di lunghezza massima di 5 caratteri e con valori ammessi [a-z], [A-Z], [0-9].
  208.        
  209.         if(idPaeseTrasmittente==null){
  210.             throw new ProtocolException("IdPaeseTrasmittente non fornito (richiesto per la creazione del nome di file)");
  211.         }
  212.         if(idCodiceTrasmittente==null){
  213.             throw new ProtocolException("IdCodiceTrasmittente non fornito (richiesto per la creazione del nome di file)");
  214.         }
  215.         String idPaeseIdCodice = idPaeseTrasmittente+idCodiceTrasmittente;
  216.        
  217.         ConfigurazionePdD config = factory.getConfigurazionePdD();
  218.        
  219.         IDSerialGenerator serialGenerator = new IDSerialGenerator(config.getLog(),state, config.getTipoDatabase());
  220.        
  221.         IDSerialGeneratorParameter serialGeneratorParameter = new IDSerialGeneratorParameter(factory.getProtocol());
  222.         serialGeneratorParameter.setSerializableTimeWaitMs(config.getAttesaAttivaJDBC());
  223.         serialGeneratorParameter.setSerializableNextIntervalTimeMs(config.getCheckIntervalJDBC());
  224.         serialGeneratorParameter.setTipo(IDSerialGeneratorType.ALFANUMERICO);
  225.         serialGeneratorParameter.setWrap(false);
  226.         serialGeneratorParameter.setSize(5);
  227.         serialGeneratorParameter.setInformazioneAssociataAlProgressivo(idPaeseIdCodice);
  228.        
  229.         String ext = "."+SDICostanti.SDI_FATTURA_ESTENSIONE_XML;
  230.         if(SDICostanti.SDI_TIPO_FATTURA_ZIP.equals(formatoInvio)){
  231.             ext = "."+SDICostanti.SDI_FATTURA_ESTENSIONE_ZIP;
  232.         }else if(SDICostanti.SDI_TIPO_FATTURA_P7M.equals(formatoInvio)){
  233.             ext = "."+SDICostanti.SDI_FATTURA_ESTENSIONE_P7M;
  234.         }
  235.        
  236.         return idPaeseIdCodice+"_"+serialGenerator.buildID(serialGeneratorParameter)+ext;
  237.     }
  238.    
  239.     public static List<byte[]> splitLotto(byte[] lotto) throws Exception {
  240.        
  241.         List<byte[]> risultato = new ArrayList<byte[]>();
  242.        
  243.         AbstractXMLUtils xmlUtils = XMLUtils.getInstance();
  244.         XPathExpressionEngine xpathEngine = new XPathExpressionEngine();
  245.        
  246.         Element lottoElement = null;
  247.         DynamicNamespaceContext dnc = null;
  248.         try{
  249.             lottoElement = xmlUtils.newElement(lotto);
  250.             dnc = new DynamicNamespaceContext();
  251.             dnc.findPrefixNamespace(lottoElement);
  252.         }catch(Exception e){
  253.             throw new Exception("Lettura lotto di fattura non riuscita: "+e.getMessage(),e);
  254.         }
  255.        
  256.         NodeList nl = null;
  257.         try{
  258.             nl = (NodeList) xpathEngine.getMatchPattern(lottoElement, dnc, "//FatturaElettronicaBody", XPathReturnType.NODESET);
  259.         }catch(XPathNotFoundException notFound){
  260.             throw new Exception("La fattura non contiene alcun body?: "+notFound.getMessage(),notFound);
  261.         }catch(Exception e){
  262.             throw new Exception("Estrazione body dal lotto di fattura non riuscita: "+e.getMessage(),e);
  263.         }
  264.         if(nl==null){
  265.             throw new Exception("La fattura non contiene alcun body? (null)");
  266.         }
  267.         if(nl.getLength()<1){
  268.             throw new Exception("La fattura non contiene alcun body? (size): "+nl.getLength());
  269.         }
  270.        
  271.         if(nl.getLength()==1){
  272.             // non si tratta di un lotto, ma di una fattura con un body solamente
  273.             risultato.add(lotto);
  274.             return risultato;
  275.         }
  276.        
  277.         List<Node> listBody = new ArrayList<Node>();
  278.         try{
  279.             for (int i = 0; i < nl.getLength(); i++) {
  280.                 Node n = nl.item(i);
  281.                 listBody.add(n);
  282.                 lottoElement.removeChild(n);
  283.             }
  284.         }catch(Exception e){
  285.             throw new Exception("Elaborazione lotto di fattura (step1) non riuscita: "+e.getMessage(),e);
  286.         }
  287.         int i = 0;
  288.         try{
  289.             for (; i < listBody.size(); i++) {
  290.                 Node n = listBody.get(i);
  291.                 lottoElement.appendChild(n);
  292.                 risultato.add(xmlUtils.toByteArray(lottoElement));
  293.                 lottoElement.removeChild(n);
  294.             }
  295.         }catch(Exception e){
  296.             throw new Exception("Elaborazione lotto di fattura (step2-"+i+") non riuscita: "+e.getMessage(),e);
  297.         }
  298.        
  299.         return risultato;
  300.     }
  301.    
  302. }