SPCoopValidazioneConSchema.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.spcoop.validator;

  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.InputStream;
  24. import java.util.HashMap;
  25. import java.util.Iterator;

  26. import javax.xml.soap.SOAPBody;
  27. import javax.xml.soap.SOAPElement;

  28. import org.openspcoop2.message.OpenSPCoop2Message;
  29. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  30. import org.openspcoop2.message.constants.MessageType;
  31. import org.openspcoop2.message.xml.ValidatoreXSD;
  32. import org.openspcoop2.message.xml.MessageXMLUtils;
  33. import org.openspcoop2.protocol.basic.BasicStateComponentFactory;
  34. import org.openspcoop2.protocol.sdk.Eccezione;
  35. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  36. import org.openspcoop2.protocol.sdk.ProtocolException;
  37. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  38. import org.openspcoop2.protocol.sdk.constants.ContestoCodificaEccezione;
  39. import org.openspcoop2.protocol.sdk.constants.LivelloRilevanza;
  40. import org.openspcoop2.protocol.sdk.state.IState;
  41. import org.openspcoop2.protocol.sdk.validator.IValidazioneConSchema;
  42. import org.openspcoop2.protocol.spcoop.SPCoopBustaRawContent;
  43. import org.openspcoop2.protocol.spcoop.config.SPCoopProperties;
  44. import org.openspcoop2.utils.LoggerWrapperFactory;
  45. import org.openspcoop2.utils.xml.XSDResourceResolver;
  46. import org.slf4j.Logger;
  47. import org.w3c.dom.Element;
  48. import org.xml.sax.SAXException;

  49. /**
  50.  * Classe che implementa, in base al protocollo SPCoop, l'interfaccia {@link org.openspcoop2.protocol.sdk.validator.IValidazioneConSchema}
  51.  * Utilizzata per effettuare una validazione con schema xsd di SPCoop.
  52.  *
  53.  * @author Poli Andrea (apoli@link.it)
  54.  * @author $Author$
  55.  * @version $Rev$, $Date$
  56.  */
  57. public class SPCoopValidazioneConSchema extends BasicStateComponentFactory implements IValidazioneConSchema {

  58.     /** Validatore della busta SPCoop */
  59.     private static HashMap<String, ValidatoreXSD> validatoreBustaSPCoop_map = new HashMap<String, ValidatoreXSD>();

  60.    
  61.    
  62.     /** Errori di validazione riscontrati sulla busta */
  63.     private java.util.List<Eccezione> erroriValidazione;
  64.     /** Errori di processamento riscontrati sulla busta */
  65.     private java.util.List<Eccezione> erroriProcessamento;

  66.    
  67.    
  68.    
  69.     /**
  70.      * Costruttore.
  71.      *
  72.      * @param protocolFactory ProtocolFactory
  73.      * @throws ProtocolException
  74.      *
  75.      */
  76.     public SPCoopValidazioneConSchema(IProtocolFactory<?> protocolFactory,IState state) throws ProtocolException{
  77.         super(protocolFactory, state);      
  78.     }


  79.     /**
  80.      * Ritorna un List contenente eventuali eccezioni di validazione riscontrate nella busta SPCoop.  
  81.      *
  82.      * @return Eccezioni riscontrate nella busta SPCoop.
  83.      *
  84.      */
  85.     @Override
  86.     public java.util.List<Eccezione> getEccezioniValidazione(){
  87.         return this.erroriValidazione;
  88.     }
  89.     /**
  90.      * Ritorna un List contenente eventuali eccezioni di processamento riscontrate nella busta SPCoop.  
  91.      *
  92.      * @return Eccezioni riscontrate nella busta SPCoop.
  93.      *
  94.      */
  95.     @Override
  96.     public java.util.List<Eccezione> getEccezioniProcessamento(){
  97.         return this.erroriProcessamento;
  98.     }

  99.     /**
  100.      * Metodo che si occupa di inizializzare lo schema della busta SPCoop utilizzato per la validazione.
  101.      *
  102.      *
  103.      */
  104.     public static synchronized boolean initializeSchema(OpenSPCoop2MessageFactory messageFactory, Logger log) {
  105.         String key = messageFactory.getClass().getName();
  106.            
  107.         if(!validatoreBustaSPCoop_map.containsKey(key)) {
  108.            
  109.             if(log==null)
  110.                 log = LoggerWrapperFactory.getLogger("ValidazioneConSchemaSPCoop");
  111.            
  112.             try{
  113.                 SPCoopProperties spcoopProperties = SPCoopProperties.getInstance(log);
  114.                
  115.                 log.info("Inizializzazione dello schema per il protocollo spcoop (possono essere necessari alcuni minuti...)");
  116.                 String[] schemiXSDDaImportare = spcoopProperties.getSchemiXSDImportatiValidazioneXSDBusta();
  117.                 String schemaXSD = spcoopProperties.getSchemaXSDValidazioneXSDBusta();
  118.                 ValidatoreXSD val = SPCoopValidazioneConSchema.createSchemaValidator(messageFactory, log,schemiXSDDaImportare, schemaXSD);
  119.                 validatoreBustaSPCoop_map.put(key, val);
  120.                 log.info("Inizializzazione dello schema per il protocollo spcoop terminata.");
  121.                 return true;
  122.             }catch (Exception e) {
  123.                 log.error("Riscontrato errore durante l'inizializzazione dello schema per il protocollo spcoop: "+e.getMessage(),e);
  124.                 return false;
  125.             }
  126.            
  127.         }
  128.        
  129.         return true; // gia' inizializzato
  130.     }

  131.     private static ValidatoreXSD getValidatoreXSD(OpenSPCoop2MessageFactory messageFactory, Logger log) {

  132.         String key = messageFactory.getClass().getName();
  133.        
  134.         if(!validatoreBustaSPCoop_map.containsKey(key)) {
  135.             initializeSchema(messageFactory, log);
  136.         }
  137.        
  138.         return validatoreBustaSPCoop_map.get(key);
  139.        
  140.     }
  141.    
  142.     private static ValidatoreXSD createSchemaValidator(OpenSPCoop2MessageFactory messageFactory,Logger log,String[] schemiXSDDaImportare,String schemaXSD) throws Exception{
  143.         // ** Schemi importati **
  144.         XSDResourceResolver xsdResourceResolver = new XSDResourceResolver();
  145.         if(schemiXSDDaImportare!=null){
  146.             for(int i=0;i<schemiXSDDaImportare.length;i++){
  147.                 File fXsd = new File(schemiXSDDaImportare[i]);
  148.                 InputStream is = null;
  149.                 try{
  150.                     if(fXsd.exists()){
  151.                         is = new FileInputStream(fXsd);
  152.                     }else{
  153.                         is = SPCoopValidazioneConSchema.class.getResourceAsStream("/"+schemiXSDDaImportare[i]);
  154.                     }
  155.                     xsdResourceResolver.addResource(fXsd.getName(), is);
  156.                 }finally{
  157.                     try{
  158.                         if(is!=null){
  159.                             is.close();
  160.                         }
  161.                     }catch(Exception e){
  162.                         // close
  163.                     } //?????? Close effettuato dentro xsdResolver ??? : riabilitato il close.
  164.                 }
  165.             }
  166.         }
  167.        
  168.         // ** Schema principale **
  169.         File fXsd = new File(schemaXSD);
  170.         InputStream is = null;
  171.         try{
  172.             if(fXsd.exists()){
  173.                 is = new FileInputStream(fXsd);
  174.             }else{
  175.                 is = SPCoopValidazioneConSchema.class.getResourceAsStream("/"+schemaXSD);
  176.             }
  177.             // ** Creo Validatore **
  178.             return new ValidatoreXSD(messageFactory,log,xsdResourceResolver,is);
  179.         }finally{
  180.             try{
  181.                 if(is!=null){
  182.                     is.close();
  183.                 }
  184.             }catch(Exception e){
  185.                 // close
  186.             } //?????? Close effettuato dentro xsdResolver ???? : riabilitato il close.
  187.         }
  188.        
  189.     }
  190.    
  191.     /**
  192.      * Metodo che effettua la validazione dei soggetti di una busta, controllando la loro registrazione nel registro dei servizi.
  193.      *
  194.      * Mano mano che sono incontrati errori di validazione, viene creato un oggetto
  195.      *   {@link Eccezione}, e viene inserito nel List <var>errors</var>.
  196.      *
  197.      *
  198.      */
  199.     @Override
  200.     public void valida(OpenSPCoop2Message message, boolean isSPCoopErroreProcessamento, boolean isSPCoopErroreIntestazione,
  201.             boolean isMessaggioConAttachments, boolean validazioneManifestAttachments) throws ProtocolException{

  202.         this.erroriValidazione = new java.util.ArrayList<Eccezione>();
  203.         this.erroriProcessamento = new java.util.ArrayList<Eccezione>();

  204.         MessageXMLUtils xmlUtils = MessageXMLUtils.getInstance(message.getFactory());
  205.         ValidatoreXSD validatoreBustaSPCoop = getValidatoreXSD(message.getFactory(), this.log);
  206.        
  207.         if(validatoreBustaSPCoop == null){
  208.             throw new ProtocolException("Validatore con schema XSD non inizializzato");
  209.         }    
  210.        
  211.         // Validazione eGov
  212.         try {

  213.             SPCoopBustaRawContent bustaElement = (SPCoopBustaRawContent) this.protocolFactory.createValidazioneSintattica(this.state).getBustaRawContent_senzaControlli(message);
  214.             SOAPElement header = bustaElement.getElement();
  215.            
  216.             if(isSPCoopErroreProcessamento==false && isSPCoopErroreIntestazione==false){
  217.                
  218.                 // VALIDAZIONE
  219.                 validatoreBustaSPCoop.valida(
  220.                         xmlUtils.newDocument(OpenSPCoop2MessageFactory.getAsByte(message.getFactory(), header,false)));
  221.                
  222.             }
  223.             else{
  224.                
  225.                 // Validazione Lista Eccezioni.
  226.                 Iterator<?> itChilds = header.getChildElements();
  227.                 SOAPElement listaEccezioni = null;
  228.                 while(itChilds.hasNext()){
  229.                     Object element = itChilds.next();
  230.                     if(!(element instanceof SOAPElement)){
  231.                         continue;
  232.                     }
  233.                    
  234.                     SOAPElement elemInterno = (SOAPElement) element;
  235.                     if("ListaEccezioni".equals(elemInterno.getLocalName())){
  236.                         listaEccezioni = elemInterno;
  237.                         break;
  238.                     }
  239.                 }
  240.                 if(listaEccezioni==null){
  241.                     if(isSPCoopErroreIntestazione)
  242.                         throw new SAXException("ListaEccezioni non presente in un messaggio SPCoopErrore");
  243.                 }
  244.                
  245.                 // VALIDAZIONE
  246.                 if(listaEccezioni!=null){
  247.                     validatoreBustaSPCoop.valida(
  248.                             xmlUtils.newDocument(OpenSPCoop2MessageFactory.getAsByte(message.getFactory(), listaEccezioni,false)));
  249.                 }
  250.             }
  251.                    
  252.         } catch (SAXException e) {
  253.             // instance document is invalid!
  254.             Eccezione ecc = new Eccezione();
  255.             ecc.setContestoCodifica(ContestoCodificaEccezione.INTESTAZIONE);
  256.             ecc.setCodiceEccezione(CodiceErroreCooperazione.FORMATO_INTESTAZIONE_NON_CORRETTO);
  257.             ecc.setRilevanza(LivelloRilevanza.ERROR);
  258.             ecc.setDescrizione(e.getMessage());
  259.             this.erroriValidazione.add(ecc);
  260.         }catch (Exception e) {
  261.             Eccezione ecc = new Eccezione();
  262.             ecc.setContestoCodifica(ContestoCodificaEccezione.PROCESSAMENTO);
  263.             ecc.setCodiceEccezione(CodiceErroreCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO);
  264.             ecc.setRilevanza(LivelloRilevanza.ERROR);
  265.             ecc.setDescrizione("Validazione con schema xsd dell'header egov non riuscita: errore di processamento");
  266.             this.log.error("Validazione con schema xsd dell'header egov non riuscita non riuscita",e);
  267.             this.erroriProcessamento.add(ecc);
  268.         }

  269.         // Validazione ManifestAttachments
  270.         SOAPBody soapBody = null;
  271.         if(validazioneManifestAttachments && isMessaggioConAttachments) {
  272.             try{
  273.                 soapBody = message.castAsSoap().getSOAPBody();
  274.             }catch(Exception e){
  275.                 throw new ProtocolException(e.getMessage(),e);
  276.             }
  277.         }
  278.         if(soapBody!=null){
  279.             try {  
  280.                 // Validazione
  281.                
  282.                 Element firstElement = OpenSPCoop2MessageFactory.getFirstChildElement(message.getFactory(), MessageType.SOAP_11, soapBody);
  283.                 //validatoreBustaSPCoop.valida(xmlUtils.newDocument(OpenSPCoop2MessageFactory.getAsByte(message.getFactory(), firstElement, false)));
  284.                 validatoreBustaSPCoop.valida(firstElement);
  285.             } catch (SAXException e) {
  286.                 // instance document is invalid!
  287.                 Eccezione ecc = new Eccezione();
  288.                 ecc.setContestoCodifica(ContestoCodificaEccezione.INTESTAZIONE);
  289.                 ecc.setCodiceEccezione(CodiceErroreCooperazione.FORMATO_CORPO_NON_CORRETTO);
  290.                 ecc.setRilevanza(LivelloRilevanza.ERROR);
  291.                 ecc.setDescrizione("ManifestAttachments: "+e.getMessage());
  292.                 this.log.error("Validazione con schema xsd del manifest degli attachments fallita",e);
  293.                 this.erroriValidazione.add(ecc);
  294.             }catch (Exception e) {
  295.                 Eccezione ecc = new Eccezione();
  296.                 ecc.setContestoCodifica(ContestoCodificaEccezione.PROCESSAMENTO);
  297.                 ecc.setCodiceEccezione(CodiceErroreCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO);
  298.                 ecc.setRilevanza(LivelloRilevanza.ERROR);
  299.                 ecc.setDescrizione("Validazione con schema xsd del manifest degli attachments non riuscita: errore di processamento");
  300.                 this.log.error("Validazione con schema xsd del manifest degli attachments non riuscita",e);
  301.                 this.erroriProcessamento.add(ecc);
  302.             }
  303.         }

  304.     }

  305.     @Override
  306.     public boolean initialize(OpenSPCoop2MessageFactory messageFactory) {
  307.         return SPCoopValidazioneConSchema.initializeSchema(messageFactory, this.log);
  308.     }

  309. }