XMLUtils.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 it.cnipa.collprofiles.driver;

  21. import java.io.ByteArrayInputStream;
  22. import java.io.ByteArrayOutputStream;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.InputStream;
  26. import java.io.OutputStream;
  27. import java.util.ArrayList;
  28. import java.util.HashMap;
  29. import java.util.List;
  30. import java.util.Map;

  31. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  32. import org.openspcoop2.core.registry.Operation;
  33. import org.openspcoop2.core.registry.PortType;
  34. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  35. import org.openspcoop2.core.registry.constants.ProfiloCollaborazione;
  36. import org.openspcoop2.core.registry.constants.StatoFunzionalita;
  37. import org.openspcoop2.core.registry.wsdl.RegistroOpenSPCoopUtilities;
  38. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  39. import org.openspcoop2.utils.wsdl.DefinitionWrapper;
  40. import org.openspcoop2.utils.xml.AbstractXMLUtils;
  41. import org.openspcoop2.utils.xml.JaxbUtils;
  42. import org.openspcoop2.utils.xml.ValidatoreXSD;
  43. import org.slf4j.Logger;
  44. import org.w3c.dom.Attr;
  45. import org.w3c.dom.Document;
  46. import org.w3c.dom.Element;
  47. import org.w3c.dom.NamedNodeMap;
  48. import org.w3c.dom.Node;

  49. import it.cnipa.collprofiles.EgovDecllElement;
  50. import it.cnipa.collprofiles.OperationListType;
  51. import it.cnipa.collprofiles.OperationType;
  52. import it.cnipa.collprofiles.constants.ProfiloDiCollaborazioneType;
  53. import it.gov.spcoop.sica.manifest.driver.TipiDocumentoSemiformale;


  54. /**
  55.  * Classe utilizzata per lavorare sul documento semiformale che contiene le informazioni eGov dei servizi di un accordo
  56.  *
  57.  *
  58.  * @author Poli Andrea (apoli@link.it)
  59.  * @author $Author$
  60.  * @version $Rev$, $Date$
  61.  */

  62. public class XMLUtils  {

  63.     /** Validatore XSD */
  64.     static ValidatoreXSD validatoreXSD = null;
  65.     public static synchronized ValidatoreXSD getValidatoreXSD(Logger log) throws Exception{
  66.         if(XMLUtils.validatoreXSD==null){
  67.             XMLUtils.validatoreXSD = new ValidatoreXSD(log,XMLUtils.class.getResourceAsStream("/SpecificaSemiformaleEGov.xsd"));
  68.         }
  69.         return XMLUtils.validatoreXSD;
  70.     }
  71.     public static boolean validate(EgovDecllElement egov,StringBuilder motivoErroreValidazione){
  72.        
  73.         int size = motivoErroreValidazione.length();
  74.        
  75.         if(egov.getEGovVersion()==null){
  76.             motivoErroreValidazione.append("VersioneEGov non definita\n");
  77.         }
  78.         if(egov.getRifDefinizioneInterfaccia()==null){
  79.             motivoErroreValidazione.append("RifInterfaccia non definita\n");
  80.         }
  81.        
  82.         OperationListType operations = egov.getOperationList();
  83.         if(operations == null){
  84.             motivoErroreValidazione.append("OperationListType non presente\n");
  85.         }else{
  86.             if(operations.sizeOperationList()<=0){
  87.                 motivoErroreValidazione.append("OperationListType vuota\n");
  88.             }
  89.             for(int i=0; i<operations.sizeOperationList(); i++){
  90.                 OperationType op = operations.getOperation(i);
  91.                 if(op.getServizio()==null){
  92.                     motivoErroreValidazione.append("OperationList["+i+"] senza il servizio\n");
  93.                 }
  94.                 if(op.getOperazione()==null){
  95.                     motivoErroreValidazione.append("OperationList["+i+"] senza l'operation\n");
  96.                 }
  97.                 if(op.getProfiloDiCollaborazione()==null){
  98.                     motivoErroreValidazione.append("OperationList["+i+"] senza un profilo di collaborazione\n");
  99.                 }
  100.                 if(ProfiloDiCollaborazioneType.ONE_WAY.equals(op.getProfiloDiCollaborazione())==false &&
  101.                         ProfiloDiCollaborazioneType.SINCRONO.equals(op.getProfiloDiCollaborazione())==false &&
  102.                                 ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(op.getProfiloDiCollaborazione())==false &&
  103.                                         ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(op.getProfiloDiCollaborazione())==false ){
  104.                     motivoErroreValidazione.append("OperationList["+i+"] con un profilo di collaborazione non conosciuto ("+op.getProfiloDiCollaborazione()+")\n");
  105.                 }
  106.             }
  107.         }
  108.        
  109.         if(motivoErroreValidazione.length()!=size)
  110.             return false;
  111.         else
  112.             return true;

  113.     }
  114.    
  115.    
  116.    
  117.    
  118.     /* ----- Unmarshall ----- */
  119.    
  120.     /**
  121.      * Ritorna la rappresentazione java
  122.      *
  123.      * @param m byte[]
  124.      * @return EgovDeclType
  125.      * @throws XMLUtilsException
  126.      */
  127.     public static EgovDecllElement getDichiarazioneEGov(Logger log,byte[] m,boolean acceptChildUnqualified) throws XMLUtilsException{
  128.         ByteArrayInputStream bin = null;
  129.         try{
  130.             bin = new ByteArrayInputStream(m);
  131.             return XMLUtils.getDichiarazioneEGov(log,bin,acceptChildUnqualified);
  132.         }catch(Exception e){
  133.             throw new XMLUtilsException(e.getMessage(),e);
  134.         }finally{
  135.             try{
  136.                 if(bin!=null)
  137.                     bin.close();
  138.             }catch(Exception eClose){
  139.                 // close
  140.             }
  141.         }
  142.     }
  143.    
  144.     /**
  145.      * Ritorna la rappresentazione java
  146.      *
  147.      * @param m File
  148.      * @return EgovDeclType
  149.      * @throws XMLUtilsException
  150.      */
  151.     public static EgovDecllElement getDichiarazioneEGov(Logger log,File m,boolean acceptChildUnqualified) throws XMLUtilsException{
  152.         FileInputStream fin = null;
  153.         try{
  154.             fin = new FileInputStream(m);
  155.             return XMLUtils.getDichiarazioneEGov(log,fin,acceptChildUnqualified);
  156.         }catch(Exception e){
  157.             throw new XMLUtilsException(e.getMessage(),e);
  158.         }finally{
  159.             try{
  160.                 if(fin!=null)
  161.                     fin.close();
  162.             }catch(Exception eClose){
  163.                 // close
  164.             }
  165.         }
  166.     }
  167.    
  168.     /**
  169.      * Ritorna la rappresentazione java
  170.      *
  171.      * @param m String
  172.      * @return EgovDeclType
  173.      * @throws XMLUtilsException
  174.      */
  175.     public static EgovDecllElement getDichiarazioneEGov(Logger log,String m,boolean acceptChildUnqualified) throws XMLUtilsException{
  176.         return XMLUtils.getDichiarazioneEGov(log,m.getBytes(),acceptChildUnqualified);
  177.     }
  178.    
  179.     /**
  180.      * Ritorna la rappresentazione java
  181.      *
  182.      * @param m InputStream
  183.      * @return EgovDeclType
  184.      * @throws XMLUtilsException
  185.      */
  186.     public static EgovDecllElement getDichiarazioneEGov(Logger log,InputStream m,boolean acceptChildUnqualified) throws XMLUtilsException{
  187.         try{
  188.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  189.             byte[]reads = new byte[1024];
  190.             int letti = 0;
  191.             while( (letti=m.read(reads)) != -1){
  192.                 bout.write(reads, 0, letti);
  193.             }
  194.             bout.flush();
  195.             bout.close();
  196.             byte [] xml = bout.toByteArray();
  197.            
  198.             // Modifico namespace spcoop.gov.it in  www.cnipa.it
  199.             // Altrimenti la validazione XSD fallisce.
  200.             // Viene effettuato questa trasformazione per accettare comunque gli xml con il namespace spcoop.gov.it
  201.             if(XMLUtils.isProfiloCollaborazioneEGOV_NamespaceSPCoopGovIT(xml)){
  202.                 xml = bout.toString().replaceAll("spcoop\\.gov\\.it","www.cnipa.it").getBytes();
  203.             }
  204.            
  205.             // il Client SICA permette di costruire XML che possiedono un prefix nel root element,
  206.             // ma negli elementi interni tale prefix non viene utilizzato.
  207.             // Es:
  208.             // <tns:egovDecllElement xmlns:tns="http://spcoop.gov.it/collProfiles" ...>
  209.             //      <e-govVersion>....
  210.             // Questo XML non e' validabile rispetto all'XSD poiche' e-govVersion non e' qualificato.
  211.             if(acceptChildUnqualified){
  212.                 xml = XMLUtils.unescapeXMLMalformatoChildElements(xml);
  213.             }
  214.            
  215.             // Validazione XSD
  216.             ByteArrayInputStream binValidazione = new ByteArrayInputStream(xml);
  217.             ValidatoreXSD validatoreXSD = XMLUtils.getValidatoreXSD(log);
  218.             validatoreXSD.valida(binValidazione);
  219.            
  220.             // trasformazione in oggetto EgovDecllElement
  221.             ByteArrayInputStream binTrasformazione = new ByteArrayInputStream(xml);
  222.             return (EgovDecllElement) JaxbUtils.xmlToObj(binTrasformazione, EgovDecllElement.class);
  223.            
  224.         }catch(Exception e){
  225.             throw new XMLUtilsException(e.getMessage(),e);
  226.         }
  227.     }
  228.    
  229.     private static byte [] unescapeXMLMalformatoChildElements(byte [] xml){
  230.         try{
  231.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  232.             Document docXML = xmlUtils.newDocument(xml);
  233.             Element elemXML = docXML.getDocumentElement();
  234.             String prefixRootElement = elemXML.getPrefix();
  235.             String prefixChildElementEgovVersione = null;
  236.             for(int i=0; i< elemXML.getChildNodes().getLength(); i++){
  237.                 Node child = elemXML.getChildNodes().item(i);
  238.                 if(Costanti.CHILD_ELEMENT_EGOV_VERSIONE_LOCAL_NAME.equals(child.getLocalName())){
  239.                     prefixChildElementEgovVersione = child.getPrefix();
  240.                 }
  241.             }
  242.             if(prefixRootElement!=null && prefixChildElementEgovVersione==null){
  243.                 String xmlS = new String(xml);
  244.                 xmlS = xmlS.replace("<"+prefixRootElement+":"+Costanti.ROOT_LOCAL_NAME,"<"+Costanti.ROOT_LOCAL_NAME);
  245.                 //xmlS = xmlS.replace("xmlns:wscp=\"http://spcoop.gov.it/sica/wscp\" xmlns","xmlns");
  246.                 xmlS = xmlS.replace("xmlns:"+prefixRootElement,"xmlns");
  247.                 xmlS = xmlS.replace("</"+prefixRootElement+":"+Costanti.ROOT_LOCAL_NAME,"</"+Costanti.ROOT_LOCAL_NAME);
  248.                 xml = xmlS.getBytes();
  249.             }
  250.            
  251.             return xml;
  252.         }catch(Exception e){
  253.             return xml; // ritorno xml senza trasformazioni
  254.         }
  255.     }
  256.    
  257.    
  258.    
  259.    
  260.     /* ----- Marshall Manifest dell'accordo di servizio ----- */
  261.     public static void generateDichiarazioneEGov(EgovDecllElement manifest,File out,boolean namespaceCnipa) throws XMLUtilsException{
  262.         try{
  263.             StringBuilder risultatoValidazione = new StringBuilder();
  264.             if(XMLUtils.validate(manifest, risultatoValidazione)==false){
  265.                 throw new Exception(risultatoValidazione.toString());
  266.             }
  267.             JaxbUtils.objToXml(out.getName(),XMLUtils.generateDichiarazioneEGov_engine(manifest, namespaceCnipa));
  268.         }catch(Exception e){
  269.             throw new XMLUtilsException(e.getMessage(),e);
  270.         }
  271.     }
  272.    
  273.     public static void generateDichiarazioneEGov(EgovDecllElement manifest,String fileName,boolean namespaceCnipa) throws XMLUtilsException{
  274.         try{
  275.             StringBuilder risultatoValidazione = new StringBuilder();
  276.             if(XMLUtils.validate(manifest, risultatoValidazione)==false){
  277.                 throw new Exception(risultatoValidazione.toString());
  278.             }
  279.             JaxbUtils.objToXml(fileName,XMLUtils.generateDichiarazioneEGov_engine(manifest, namespaceCnipa));
  280.         }catch(Exception e){
  281.             throw new XMLUtilsException(e.getMessage(),e);
  282.         }
  283.     }
  284.    
  285.     public static byte[] generateDichiarazioneEGov(EgovDecllElement manifest,boolean namespaceCnipa) throws XMLUtilsException{
  286.         try{
  287.             StringBuilder risultatoValidazione = new StringBuilder();
  288.             if(XMLUtils.validate(manifest, risultatoValidazione)==false){
  289.                 throw new Exception(risultatoValidazione.toString());
  290.             }
  291.             return XMLUtils.generateDichiarazioneEGov_engine(manifest, namespaceCnipa);
  292.         }catch(Exception e){
  293.             throw new XMLUtilsException(e.getMessage(),e);
  294.         }
  295.     }

  296.     public static void generateDichiarazioneEGov(EgovDecllElement manifest,OutputStream out,boolean namespaceCnipa) throws XMLUtilsException{
  297.         try{
  298.             StringBuilder risultatoValidazione = new StringBuilder();
  299.             if(XMLUtils.validate(manifest, risultatoValidazione)==false){
  300.                 throw new Exception(risultatoValidazione.toString());
  301.             }
  302.             out.write(XMLUtils.generateDichiarazioneEGov_engine(manifest, namespaceCnipa));
  303.             out.flush();
  304.             out.close();
  305.         }catch(Exception e){
  306.             throw new XMLUtilsException(e.getMessage(),e);
  307.         }
  308.     }
  309.    
  310.     private static byte[] generateDichiarazioneEGov_engine(EgovDecllElement manifest,boolean namespaceCnipa) throws XMLUtilsException{
  311.         try{
  312.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  313.             JaxbUtils.objToXml(bout, EgovDecllElement.class, manifest);
  314.             byte[] dichiarazione = bout.toByteArray();
  315.             if(namespaceCnipa==false){
  316.                 // Modifico namespace www.cnipa.it in spcoop.gov.it
  317.                 dichiarazione = bout.toString().replaceAll("www\\.cnipa\\.it", "spcoop.gov.it").getBytes();
  318.             }
  319.             return dichiarazione;
  320.         }catch(Exception e){
  321.             throw new XMLUtilsException(e.getMessage(),e);
  322.         }
  323.     }
  324.    
  325.    
  326.    
  327.    
  328.    
  329.    
  330.    
  331.     public static boolean isProfiloCollaborazioneEGOV(byte [] doc){
  332.         try{
  333.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  334.             Document docXML = xmlUtils.newDocument(doc);
  335.             Element elemXML = docXML.getDocumentElement();
  336.             //System.out.println("LOCAL["+Costanti.ROOT_LOCAL_NAME+"]vs["+elemXML.getLocalName()+"]  NAMESPACE["+Costanti.TARGET_NAMESPACE+"]vs["+elemXML.getNamespaceURI()+"]");
  337.             if(Costanti.ROOT_LOCAL_NAME.equals(elemXML.getLocalName()) &&
  338.                     ( Costanti.TARGET_NAMESPACE.equals(elemXML.getNamespaceURI()) || Costanti.TARGET_NAMESPACE_SPCOOP_GOV_IT.equals(elemXML.getNamespaceURI()) )
  339.                 ){
  340.                 return true;
  341.             }
  342.             else{
  343.                 return false;
  344.             }
  345.         }catch(Exception e){
  346.             //System.out.println("NON e' un DOCUMENTO VALIDO: "+e.getMessage());
  347.             return false;
  348.         }
  349.     }
  350.    
  351.     private static boolean isProfiloCollaborazioneEGOV_NamespaceSPCoopGovIT(byte [] doc){
  352.         try{
  353.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  354.             Document docXML = xmlUtils.newDocument(doc);
  355.             Element elemXML = docXML.getDocumentElement();
  356.             //System.out.println("LOCAL["+Costanti.ROOT_LOCAL_NAME+"]vs["+elemXML.getLocalName()+"]  NAMESPACE["+Costanti.TARGET_NAMESPACE+"]vs["+elemXML.getNamespaceURI()+"]");
  357.             if(Costanti.ROOT_LOCAL_NAME.equals(elemXML.getLocalName()) &&
  358.                     Costanti.TARGET_NAMESPACE_SPCOOP_GOV_IT.equals(elemXML.getNamespaceURI())  
  359.                 ){
  360.                 return true;
  361.             }
  362.             else{
  363.                 return false;
  364.             }
  365.         }catch(Exception e){
  366.             //System.out.println("NON e' un DOCUMENTO VALIDO: "+e.getMessage());
  367.             return false;
  368.         }
  369.     }
  370.    
  371.     private static String readNomeSPCoop(String QName,Map<String, String> mapPrefixNamespaces) throws XMLUtilsException{
  372.         if(QName==null){
  373.             return null; // per correlati
  374.         }
  375.         else{
  376.             if(QName.contains(":")){
  377.                 String [] split = QName.split(":");
  378.                 if(split.length!=2){
  379.                      throw new XMLUtilsException("QName ["+QName+"] non valido");
  380.                 }
  381.                 String prefix = split[0].trim();
  382.                 String nomeSPCoop = split[1].trim();
  383.                 if(mapPrefixNamespaces.containsKey(prefix)){
  384.                     //System.out.println("EFFETTUATO MAPPING IN: "+nomeSPCoop+" da ["+QName+"] del namespace ["+mapPrefixNamespaces.get(prefix)+"]");
  385.                     return nomeSPCoop;
  386.                 }else{
  387.                     throw new XMLUtilsException("QName ["+QName+"] non valido, prefix ["+prefix+"] non associato a nessun namespace");
  388.                 }
  389.             }else{
  390.                 return QName;
  391.             }
  392.         }
  393.     }
  394.    
  395.     public static void mapProfiloCollaborazioneEGOVIntoAS(Logger log,byte [] doc,AccordoServizioParteComune as,boolean acceptChildUnqualified) throws XMLUtilsException{
  396.        
  397.         // SpecificaSemiformale
  398.         EgovDecllElement egov = null;
  399.         try{
  400.             egov = XMLUtils.getDichiarazioneEGov(log,doc,acceptChildUnqualified);
  401.         }catch(Exception e){
  402.             throw new XMLUtilsException("Documento con informazione egov non leggibile: "+e.getMessage(),e);
  403.         }
  404.         // Lettura specifica come document
  405.         Map<String, String> mapPrefixNamespaces = new HashMap<>();
  406.         try{
  407.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  408.             Document docXML = xmlUtils.newDocument(doc);
  409.             Element elemXML = docXML.getDocumentElement();
  410.             NamedNodeMap map = elemXML.getAttributes();
  411.             for(int i=0;i<map.getLength();i++){
  412.                 Object o = map.item(i);
  413.                 if(o instanceof Attr){
  414.                     Attr attr = (Attr) o;
  415.                     String prefix = "";
  416.                     if(attr.getPrefix()!=null){
  417.                         prefix = attr.getLocalName(); // il prefisso sara' xmlns
  418.                     }
  419.                     mapPrefixNamespaces.put(prefix, attr.getValue());
  420.                 }
  421.             }
  422.         }catch(Exception e){
  423.             throw new XMLUtilsException("Documento XML con informazione egov non leggibile: "+e.getMessage(),e);
  424.         }
  425.                
  426.         Map<String, PortType> servizi = new HashMap<String, PortType>();
  427.         OperationListType list = egov.getOperationList();
  428.         for(int h=0; h<list.sizeOperationList(); h++){
  429.             OperationType operationType =  list.getOperation(h);
  430.             String nomeAzione = XMLUtils.readNomeSPCoop(operationType.getOperazione(),mapPrefixNamespaces);
  431.             String nomeServizio = XMLUtils.readNomeSPCoop(operationType.getServizio(),mapPrefixNamespaces);
  432.             String nomeAzioneCorrelata = XMLUtils.readNomeSPCoop(operationType.getOperazioneCorrelata(),mapPrefixNamespaces);
  433.             String nomeServizioCorrelato = XMLUtils.readNomeSPCoop(operationType.getServizioCorrelato(),mapPrefixNamespaces);
  434.             ProfiloDiCollaborazioneType profiloCollaborazione = operationType.getProfiloDiCollaborazione();
  435.            
  436.             PortType pt = null;
  437.             if(servizi.containsKey(nomeServizio)){
  438.                 pt = servizi.remove(nomeServizio);
  439.             }else{
  440.                 pt = new PortType();
  441.                 pt.setProfiloPT(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  442.                 pt.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  443.                 if(ProfiloDiCollaborazioneType.ONE_WAY.equals(profiloCollaborazione))
  444.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ONEWAY);
  445.                 else if(ProfiloDiCollaborazioneType.SINCRONO.equals(profiloCollaborazione))
  446.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.SINCRONO);
  447.                 else if(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  448.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  449.                 else if(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  450.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  451.                 else
  452.                     throw new XMLUtilsException("Profilo di collaborazione non valido ["+profiloCollaborazione+"]");
  453.                 pt.setNome(nomeServizio);
  454.             }
  455.             Operation azione = new Operation();
  456.             azione.setNome(nomeAzione);
  457.             azione.setProfAzione(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  458.             azione.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  459.             if(ProfiloDiCollaborazioneType.ONE_WAY.equals(profiloCollaborazione))
  460.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ONEWAY);
  461.             else if(ProfiloDiCollaborazioneType.SINCRONO.equals(profiloCollaborazione))
  462.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.SINCRONO);
  463.             else if(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  464.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  465.             else if(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  466.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  467.             else
  468.                 throw new XMLUtilsException("Profilo di collaborazione non valido ["+profiloCollaborazione+"]");
  469.             pt.addAzione(azione);
  470.             servizi.put(nomeServizio, pt);
  471.            
  472.             if(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(profiloCollaborazione) ||
  473.                     ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione) ){
  474.                
  475.                 if(nomeAzioneCorrelata==null){
  476.                     continue;
  477.                 }
  478.                
  479.                 String servizio = nomeServizioCorrelato;
  480.                 if(servizio==null)
  481.                     servizio= nomeServizio;
  482.                
  483.                 PortType ptCorrelato = null;
  484.                 if(servizi.containsKey(servizio)){
  485.                     ptCorrelato = servizi.remove(servizio);
  486.                 }else{
  487.                     ptCorrelato = new PortType();
  488.                     ptCorrelato.setProfiloPT(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  489.                     ptCorrelato.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  490.                     if(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  491.                         ptCorrelato.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  492.                     else if(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  493.                         ptCorrelato.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  494.                     ptCorrelato.setNome(servizio);
  495.                 }
  496.                 Operation azioneCorrelata = new Operation();
  497.                 azioneCorrelata.setNome(nomeAzioneCorrelata);
  498.                 azioneCorrelata.setProfAzione(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  499.                 azioneCorrelata.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  500.                 if(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  501.                     azioneCorrelata.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  502.                 else if(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  503.                     azioneCorrelata.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  504.                 if(nomeServizio!=null)
  505.                     azioneCorrelata.setCorrelataServizio(nomeServizio);
  506.                 azioneCorrelata.setCorrelata(nomeAzione);
  507.                 ptCorrelato.addAzione(azioneCorrelata);
  508.                
  509.                 servizi.put(servizio, ptCorrelato);
  510.             }
  511.         }
  512.        
  513.         if(servizi!=null && !servizi.isEmpty()) {
  514.             for (String pt : servizi.keySet()) {
  515.                 as.addPortType(servizi.get(pt));
  516.             }
  517.         }

  518.     }
  519.    
  520.    
  521.    
  522.    
  523.    
  524.    
  525.    
  526.    
  527.    
  528.     public static it.gov.spcoop.sica.manifest.DocumentoSemiformale generaDocumentoSemiformale(AccordoServizioParteComune as,
  529.             it.gov.spcoop.sica.dao.AccordoServizioParteComune accServParteComuneSICA,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  530.         it.gov.spcoop.sica.manifest.DocumentoSemiformale docSemiformalePerManifest = XMLUtils.generaDocumentoSemiformalePerManifesto();
  531.         it.gov.spcoop.sica.dao.Documento docSICA = XMLUtils.generaDocumentoSemiformale(as,namespaceCnipa,nomiSPCoopQualified);
  532.         accServParteComuneSICA.addSpecificaSemiformale(docSICA);
  533.         return docSemiformalePerManifest;
  534.     }
  535.     public static it.gov.spcoop.sica.manifest.DocumentoSemiformale generaDocumentoSemiformale(AccordoServizioParteComune as,
  536.             it.gov.spcoop.sica.dao.AccordoServizioComposto accServCompostoSICA,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  537.         it.gov.spcoop.sica.manifest.DocumentoSemiformale docSemiformalePerManifest = XMLUtils.generaDocumentoSemiformalePerManifesto();
  538.         it.gov.spcoop.sica.dao.Documento docSICA = XMLUtils.generaDocumentoSemiformale(as,namespaceCnipa,nomiSPCoopQualified);
  539.         accServCompostoSICA.addSpecificaSemiformale(docSICA);
  540.         return docSemiformalePerManifest;
  541.     }
  542.     private static it.gov.spcoop.sica.manifest.DocumentoSemiformale generaDocumentoSemiformalePerManifesto() throws XMLUtilsException{
  543.         it.gov.spcoop.sica.manifest.DocumentoSemiformale docSemiformale = new it.gov.spcoop.sica.manifest.DocumentoSemiformale();
  544.         docSemiformale.setTipo(TipiDocumentoSemiformale.XML.toString());
  545.         docSemiformale.setBase(it.cnipa.collprofiles.driver.Costanti.SPECIFICA_SEMIFORMALE_INFORMAZIONI_EGOV);
  546.         return docSemiformale;
  547.     }
  548.     private static it.gov.spcoop.sica.dao.Documento generaDocumentoSemiformale(AccordoServizioParteComune as,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  549.         it.gov.spcoop.sica.dao.Documento docSICA = new it.gov.spcoop.sica.dao.Documento();
  550.         docSICA.setTipo(TipiDocumentoSemiformale.XML.toString());
  551.         docSICA.setNome(it.cnipa.collprofiles.driver.Costanti.SPECIFICA_SEMIFORMALE_INFORMAZIONI_EGOV);
  552.         try{
  553.             byte[] dichiarazioneEGov = XMLUtils.generaDocumentoEGov(as, namespaceCnipa, nomiSPCoopQualified);
  554.             docSICA.setContenuto(dichiarazioneEGov);
  555.         }catch(Exception e){
  556.             throw new XMLUtilsException("Generazione dichiarazione eGov fallita: "+e.getMessage(),e);
  557.         }
  558.         return docSICA;
  559.     }
  560.    
  561.     public static String generaGenericoDocumento(AccordoServizioParteComune as,
  562.             it.gov.spcoop.sica.dao.AccordoServizioParteComune accServParteComuneSICA,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  563.         String genericoDocumentoPerManifest =  XMLUtils.generaGenericoDocumentoPerManifesto();
  564.         it.gov.spcoop.sica.dao.Documento docSICA = XMLUtils.generaGenericoDocumento(as,namespaceCnipa,nomiSPCoopQualified);
  565.         accServParteComuneSICA.addAllegato(docSICA);    
  566.         return genericoDocumentoPerManifest;
  567.     }
  568.     public static String generaGenericoDocumento(AccordoServizioParteComune as,
  569.             it.gov.spcoop.sica.dao.AccordoServizioComposto accServCompostoSICA,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  570.         String genericoDocumentoPerManifest =  XMLUtils.generaGenericoDocumentoPerManifesto();
  571.         it.gov.spcoop.sica.dao.Documento docSICA = XMLUtils.generaGenericoDocumento(as,namespaceCnipa,nomiSPCoopQualified);
  572.         accServCompostoSICA.addAllegato(docSICA);  
  573.         return genericoDocumentoPerManifest;
  574.     }
  575.     private static String generaGenericoDocumentoPerManifesto() throws XMLUtilsException{
  576.         return it.cnipa.collprofiles.driver.Costanti.SPECIFICA_SEMIFORMALE_INFORMAZIONI_EGOV;
  577.     }
  578.     private static it.gov.spcoop.sica.dao.Documento generaGenericoDocumento(AccordoServizioParteComune as,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  579.         it.gov.spcoop.sica.dao.Documento docSICA = new it.gov.spcoop.sica.dao.Documento();
  580.         docSICA.setTipo(TipiDocumentoSemiformale.XML.toString());
  581.         docSICA.setNome(it.cnipa.collprofiles.driver.Costanti.SPECIFICA_SEMIFORMALE_INFORMAZIONI_EGOV);
  582.         try{
  583.             byte[] dichiarazioneEGov = XMLUtils.generaDocumentoEGov(as, namespaceCnipa, nomiSPCoopQualified);
  584.             docSICA.setContenuto(dichiarazioneEGov);
  585.         }catch(Exception e){
  586.             throw new XMLUtilsException("Generazione dichiarazione eGov fallita: "+e.getMessage(),e);
  587.         }
  588.         return docSICA;
  589.     }
  590.    
  591.     private static byte[] generaDocumentoEGov(AccordoServizioParteComune as,boolean namespaceCnipa,boolean nomiSPCoopQualified) throws XMLUtilsException{
  592.         String prefissoNomiSPCoop = "";
  593.         String namespaceQualified = null;
  594.         if(nomiSPCoopQualified){
  595.             try{
  596.                 byte[] wsdlConcettuale = as.getByteWsdlConcettuale();
  597.                 if(wsdlConcettuale!=null){
  598.                     OpenSPCoop2MessageFactory defaultFactory = OpenSPCoop2MessageFactory.getDefaultMessageFactory();
  599.                     RegistroOpenSPCoopUtilities wsdlUtility = new RegistroOpenSPCoopUtilities(defaultFactory, null);
  600.                     wsdlConcettuale = wsdlUtility.eliminaImportASParteComune(wsdlConcettuale);
  601.                     DefinitionWrapper wsdl = new DefinitionWrapper(wsdlConcettuale,org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT);
  602.                     String targetNamespace = wsdl.getTargetNamespace();
  603.                     String prefix = null;
  604.                     if(targetNamespace!=null){
  605.                         prefix = wsdl.getPrefix(targetNamespace);
  606.                         if(prefix==null)
  607.                             prefix = "tnsService";
  608.                     }
  609.                     if(targetNamespace!=null){
  610.                         prefissoNomiSPCoop = prefix+":";
  611.                         namespaceQualified = "xmlns"+":"+prefix+"=\""+targetNamespace+"\"";
  612.                     }
  613.                 }
  614.             }catch(Exception e){
  615.                 // errore non importantissimo. Se non vi e' un corretto wsdl, non viene utilizzato un prefisso per i nomi spcoop
  616.                 System.out.println("errore durante la lettura del target namespace del wsdl: "+e.getMessage());
  617.             }
  618.         }
  619.         byte[] dichiarazioneEGov = XMLUtils.generateDichiarazioneEGov(XMLUtils.generaProfiloCollaborazioneEGOV(as,prefissoNomiSPCoop),namespaceCnipa);
  620.         if(nomiSPCoopQualified && namespaceQualified!=null){
  621.             dichiarazioneEGov = new String(dichiarazioneEGov).replaceFirst(Costanti.ROOT_LOCAL_NAME, Costanti.ROOT_LOCAL_NAME+" "+namespaceQualified).getBytes();
  622.         }
  623.         return dichiarazioneEGov;
  624.     }
  625.    
  626.     private static EgovDecllElement generaProfiloCollaborazioneEGOV(AccordoServizioParteComune as,String prefissoNomiSPCoop) throws XMLUtilsException{
  627.        
  628.         if(as.sizePortTypeList()>0){
  629.             EgovDecllElement egov = new EgovDecllElement();
  630.            
  631.             egov.setEGovVersion(it.cnipa.collprofiles.driver.Costanti.VERSIONE_BUSTA);
  632.             try {
  633.                 java.net.URI uri = new java.net.URI(as.getNome());
  634.                 egov.setRifDefinizioneInterfaccia(uri);
  635.             }catch(Exception e) {
  636.                 throw new XMLUtilsException(e.getMessage(),e);
  637.             }
  638.            
  639.             OperationListType operations = new OperationListType();
  640.            
  641.             List<OperationType> operationsSICA_asincrone_nonAncoraInserite = new ArrayList<OperationType>();
  642.                    
  643.             for(int i=0; i<as.sizePortTypeList(); i++){
  644.                
  645.                 PortType pt = as.getPortType(i);
  646.                 String nomeServizio = prefissoNomiSPCoop+pt.getNome();
  647.                
  648.                 for(int j=0; j<pt.sizeAzioneList(); j++){
  649.                    
  650.                     Operation op = pt.getAzione(j);
  651.                    
  652.                     String nomeAzione = prefissoNomiSPCoop+op.getNome();
  653.                     String nomeAzioneCorrelata = op.getCorrelata();
  654.                     if(nomeAzioneCorrelata!=null)
  655.                         nomeAzioneCorrelata=prefissoNomiSPCoop+nomeAzioneCorrelata;
  656.                     String nomeServizioCorrelato = op.getCorrelataServizio();
  657.                     if(nomeServizioCorrelato!=null)
  658.                         nomeServizioCorrelato=prefissoNomiSPCoop+nomeServizioCorrelato;
  659.            
  660.                     ProfiloCollaborazione profilo = null;
  661.                     if(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO.equals(op.getProfAzione())){
  662.                         profilo = op.getProfiloCollaborazione();
  663.                     }else{
  664.                         profilo = pt.getProfiloCollaborazione();
  665.                     }
  666.                     if(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO.equals(profilo) ||  CostantiRegistroServizi.ASINCRONO_SIMMETRICO.equals(profilo)){
  667.                        
  668.                         // Nel profilo asincrono asimmetrico il registro dei servizi di openspcoop dispone delle informazioni
  669.                         // necessarie per la correlazione.
  670.                         // Per l'asincrono simmetrico invece no.
  671.                         // Comunque anche per l'asincrono asimmetrico dove vengono usati due servizi correlati tale fatto non succede.
  672.                         // Questo aspetto viene gestito come segue:
  673.                         // Se l'operation e' null, viene tenuta in memoria tale operation (asincrona senza correlazione)
  674.                         // Se poi e' presente un'altra azione che contiene la correlazione, tale operation non sara' inserita.
  675.                        
  676.                         if(nomeAzioneCorrelata==null){
  677.                            
  678.                             // Vedo dopo se aggiungerlo
  679.                            
  680.                             OperationType opSICA = new OperationType();
  681.                             opSICA.setOperazione(nomeAzione);
  682.                             if(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO.equals(profilo))
  683.                                 opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO);
  684.                             else if(CostantiRegistroServizi.ASINCRONO_SIMMETRICO.equals(profilo))
  685.                                 opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO);
  686.                             opSICA.setServizio(nomeServizio);
  687.                             operationsSICA_asincrone_nonAncoraInserite.add(opSICA);
  688.                         }else{
  689.                            
  690.                             // Operazione asincrono con info correlata
  691.                            
  692.                             OperationType opSICA = new OperationType();
  693.                             opSICA.setOperazione(nomeAzioneCorrelata);
  694.                             opSICA.setOperazioneCorrelata(nomeAzione);
  695.                             if(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO.equals(profilo))
  696.                                 opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.ASINCRONO_ASIMMETRICO);
  697.                             else if(CostantiRegistroServizi.ASINCRONO_SIMMETRICO.equals(profilo))
  698.                                 opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.ASINCRONO_SIMMETRICO);
  699.                             if(nomeServizioCorrelato!=null)
  700.                                 opSICA.setServizio(nomeServizioCorrelato);
  701.                             else
  702.                                 opSICA.setServizio(nomeServizio);
  703.                             opSICA.setServizioCorrelato(nomeServizio);
  704.                             operations.addOperation(opSICA);
  705.                         }
  706.                     }else{
  707.                         OperationType opSICA = new OperationType();
  708.                         opSICA.setOperazione(nomeAzione);
  709.                         if(CostantiRegistroServizi.ONEWAY.equals(profilo))
  710.                             opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.ONE_WAY);
  711.                         else if(CostantiRegistroServizi.SINCRONO.equals(profilo))
  712.                             opSICA.setProfiloDiCollaborazione(ProfiloDiCollaborazioneType.SINCRONO);
  713.                         opSICA.setServizio(nomeServizio);
  714.                         operations.addOperation(opSICA);
  715.                     }
  716.                    
  717.                 }
  718.             }
  719.            
  720.            
  721.             // check operazioni non ancora inserite
  722.             while(operationsSICA_asincrone_nonAncoraInserite.size()>0){
  723.                 OperationType opSICA = operationsSICA_asincrone_nonAncoraInserite.remove(0);
  724.                 boolean find = false;
  725.                 for(int i=0;i<operations.sizeOperationList();i++){
  726.                     if(opSICA.getServizio().equals(operations.getOperation(i).getServizio()) &&
  727.                             opSICA.getOperazione().equals(operations.getOperation(i).getOperazione()) ){
  728.                         find =  true;
  729.                         break;
  730.                     }
  731.                 }
  732.                 if(find==false){
  733.                     operations.addOperation(opSICA);
  734.                 }
  735.             }
  736.            
  737.            
  738.             egov.setOperationList(operations);
  739.            
  740.             return egov;
  741.         }
  742.         else {
  743.             throw new  XMLUtilsException("PortTypes non definiti per l'accordo di servizio");
  744.         }
  745.     }
  746. }