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.gov.spcoop.sica.wscp.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.FileOutputStream;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.util.ArrayList;
  29. import java.util.HashMap;
  30. import java.util.List;
  31. import java.util.Map;

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

  50. import it.gov.spcoop.sica.manifest.driver.TipiDocumentoSemiformale;
  51. import it.gov.spcoop.sica.wscp.OperationListType;
  52. import it.gov.spcoop.sica.wscp.OperationType;
  53. import it.gov.spcoop.sica.wscp.ProfiloCollaborazioneEGOV;
  54. import it.gov.spcoop.sica.wscp.constants.ProfiloDiCollaborazioneType;


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

  63. public class XMLUtils  {

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

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

  291.     public static void generateDichiarazioneEGov(ProfiloCollaborazioneEGOV manifest,OutputStream out,boolean buildChildUnqualified) throws XMLUtilsException{
  292.         try{
  293.             byte[] xml = XMLUtils.generateDichiarazioneEGov_engine(manifest, buildChildUnqualified);
  294.             out.write(xml);    
  295.         }catch(Exception e){
  296.             throw new XMLUtilsException(e.getMessage(),e);
  297.         }
  298.     }
  299.    
  300.     private static byte[] generateDichiarazioneEGov_engine(ProfiloCollaborazioneEGOV manifest,boolean buildChildUnqualified) throws Exception{
  301.        
  302.         StringBuilder risultatoValidazione = new StringBuilder();
  303.         if(XMLUtils.validate(manifest, risultatoValidazione)==false){
  304.             throw new Exception(risultatoValidazione.toString());
  305.         }
  306.        
  307.         ByteArrayOutputStream bout = new ByteArrayOutputStream();
  308.         JaxbUtils.objToXml(bout, ProfiloCollaborazioneEGOV.class, manifest);
  309.         byte[] xml = bout.toByteArray();
  310.        
  311.         // Il client SICA si aspetta un file wscp che possiedono un prefix nel root element wscp,
  312.         // e che negli elementi interni tale prefix non venga utilizzato.
  313.         // Se si costruisce un xml regolare (con anche gli elementi interni correttamente qualificati) il client SICA da errore
  314.         // Es di xml atteso:
  315.         // <wspc:profiloCollaborazioneEGOV xmlns:wscp="http://spcoop.gov.it/sica/wscp" ...>
  316.         //      <versioneEGOV>....
  317.         // NOTA: nel processo inverso, di lettura del file wscp, in questa classe viene effettuato l'unescape per il ClientSICA.
  318.         if(buildChildUnqualified){
  319.             xml = XMLUtils.escapeXMLForClientSICA(xml);
  320.         }
  321.        
  322.         return xml;
  323.     }
  324.    
  325.     private static byte[] escapeXMLForClientSICA(byte[] xml) throws Exception{
  326.         String xmlS = new String(xml);
  327.         xmlS = xmlS.replace("<"+Costanti.ROOT_LOCAL_NAME, "<"+Costanti.PREFIX_CLIENT_SICA+":"+Costanti.ROOT_LOCAL_NAME);
  328.         xmlS = xmlS.replace("xmlns", "xmlns:"+Costanti.PREFIX_CLIENT_SICA+"");
  329.         xmlS = xmlS.replace("</"+Costanti.ROOT_LOCAL_NAME, "</"+Costanti.PREFIX_CLIENT_SICA+":"+Costanti.ROOT_LOCAL_NAME);
  330.         return xmlS.getBytes();
  331.     }
  332.    
  333.    
  334.    
  335.    
  336.    
  337.    
  338.    
  339.    
  340.     public static boolean isProfiloCollaborazioneEGOV(byte [] doc){
  341.         try{
  342.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  343.             Document docXML = xmlUtils.newDocument(doc);
  344.             Element elemXML = docXML.getDocumentElement();
  345.             //System.out.println("LOCAL["+Costanti.ROOT_LOCAL_NAME+"]vs["+elemXML.getLocalName()+"]  NAMESPACE["+Costanti.TARGET_NAMESPACE+"]vs["+elemXML.getNamespaceURI()+"]");
  346.             if(Costanti.ROOT_LOCAL_NAME.equals(elemXML.getLocalName()) &&
  347.                     Costanti.TARGET_NAMESPACE.equals(elemXML.getNamespaceURI()) ){
  348.                 return true;
  349.             }
  350.             else{
  351.                 return false;
  352.             }
  353.         }catch(Exception e){
  354.             //System.out.println("NON e' un DOCUMENTO VALIDO: "+e.getMessage());
  355.             return false;
  356.         }
  357.     }
  358.    
  359.     private static String readNomeSPCoop(String QName,Map<String, String> mapPrefixNamespaces) throws XMLUtilsException{
  360.         if(QName==null){
  361.             return null; // per correlati
  362.         }
  363.         else{
  364.             if(QName.contains(":")){
  365.                 String [] split = QName.split(":");
  366.                 if(split.length!=2){
  367.                      throw new XMLUtilsException("QName ["+QName+"] non valido");
  368.                 }
  369.                 String prefix = split[0].trim();
  370.                 String nomeSPCoop = split[1].trim();
  371.                 if(mapPrefixNamespaces.containsKey(prefix)){
  372.                     //System.out.println("EFFETTUATO MAPPING IN: "+nomeSPCoop+" da ["+QName+"] del namespace ["+mapPrefixNamespaces.get(prefix)+"]");
  373.                     return nomeSPCoop;
  374.                 }else{
  375.                     throw new XMLUtilsException("QName ["+QName+"] non valido, prefix ["+prefix+"] non associato a nessun namespace");
  376.                 }
  377.             }else{
  378.                 return QName;
  379.             }
  380.         }
  381.     }
  382.    
  383.     public static void mapProfiloCollaborazioneEGOVIntoAS(Logger log,byte [] doc,AccordoServizioParteComune as,boolean acceptChildUnqualified) throws XMLUtilsException{

  384.         // SpecificaSemiformale
  385.         ProfiloCollaborazioneEGOV egov = null;
  386.         try{
  387.             egov = XMLUtils.getDichiarazioneEGov(log,doc,acceptChildUnqualified);
  388.         }catch(Exception e){
  389.             throw new XMLUtilsException("Documento con informazione egov non leggibile: "+e.getMessage(),e);
  390.         }
  391.         // Lettura specifica come document
  392.         Map<String, String> mapPrefixNamespaces = new HashMap<>();
  393.         try{
  394.             AbstractXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;        
  395.             Document docXML = xmlUtils.newDocument(doc);
  396.             Element elemXML = docXML.getDocumentElement();
  397.             NamedNodeMap map = elemXML.getAttributes();
  398.             for(int i=0;i<map.getLength();i++){
  399.                 Object o = map.item(i);
  400.                 if(o instanceof Attr){
  401.                     Attr attr = (Attr) o;
  402.                     String prefix = "";
  403.                     if(attr.getPrefix()!=null){
  404.                         prefix = attr.getLocalName(); // il prefisso sara' xmlns
  405.                     }
  406.                     mapPrefixNamespaces.put(prefix, attr.getValue());
  407.                 }
  408.             }
  409.         }catch(Exception e){
  410.             throw new XMLUtilsException("Documento XML con informazione egov non leggibile: "+e.getMessage(),e);
  411.         }
  412.        
  413.         Map<String, PortType> servizi = new HashMap<String, PortType>();
  414.         OperationListType list = egov.getListaCollaborazioni();
  415.         for(int h=0; h<list.sizeCollaborazioneList(); h++){
  416.             OperationType operationType =  list.getCollaborazione(h);
  417.             String nomeAzione = XMLUtils.readNomeSPCoop(operationType.getOperazione(),mapPrefixNamespaces);
  418.             String nomeServizio = XMLUtils.readNomeSPCoop(operationType.getServizio(),mapPrefixNamespaces);
  419.             String nomeAzioneCorrelata = XMLUtils.readNomeSPCoop(operationType.getOperazioneCorrelata(),mapPrefixNamespaces);
  420.             String nomeServizioCorrelato = XMLUtils.readNomeSPCoop(operationType.getServizioCorrelato(),mapPrefixNamespaces);
  421.             ProfiloDiCollaborazioneType profiloCollaborazione = operationType.getProfiloDiCollaborazione();
  422.             PortType pt = null;
  423.            
  424.             if(servizi.containsKey(nomeServizio)){
  425.                 pt = servizi.remove(nomeServizio);
  426.             }else{
  427.                 pt = new PortType();
  428.                 pt.setProfiloPT(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  429.                 pt.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  430.                 if(ProfiloDiCollaborazioneType.EGOV_IT_MESSAGGIO_SINGOLO_ONE_WAY.equals(profiloCollaborazione))
  431.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ONEWAY);
  432.                 else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_SINCRONO.equals(profiloCollaborazione))
  433.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.SINCRONO);
  434.                 else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  435.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  436.                 else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  437.                     pt.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  438.                 else
  439.                     throw new XMLUtilsException("Profilo di collaborazione non valido ["+profiloCollaborazione+"]");
  440.                 pt.setNome(nomeServizio);
  441.             }
  442.             Operation azione = new Operation();
  443.             azione.setNome(nomeAzione);
  444.             azione.setProfAzione(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  445.             azione.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  446.             if(ProfiloDiCollaborazioneType.EGOV_IT_MESSAGGIO_SINGOLO_ONE_WAY.equals(profiloCollaborazione))
  447.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ONEWAY);
  448.             else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_SINCRONO.equals(profiloCollaborazione))
  449.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.SINCRONO);
  450.             else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  451.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  452.             else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  453.                 azione.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  454.             else
  455.                 throw new XMLUtilsException("Profilo di collaborazione non valido ["+profiloCollaborazione+"]");
  456.             pt.addAzione(azione);
  457.             servizi.put(nomeServizio, pt);
  458.            
  459.             if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_SIMMETRICO.equals(profiloCollaborazione) ||
  460.                     ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione) ){
  461.                
  462.                 if(nomeAzioneCorrelata==null){
  463.                     continue;
  464.                 }
  465.                
  466.                 String servizio = nomeServizioCorrelato;
  467.                 if(servizio==null)
  468.                     servizio= nomeServizio;
  469.                
  470.                 PortType ptCorrelato = null;
  471.                 if(servizi.containsKey(servizio)){
  472.                     ptCorrelato = servizi.remove(servizio);
  473.                 }else{
  474.                     ptCorrelato = new PortType();
  475.                     ptCorrelato.setProfiloPT(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  476.                     ptCorrelato.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  477.                     if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  478.                         ptCorrelato.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  479.                     else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  480.                         ptCorrelato.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  481.                     ptCorrelato.setNome(servizio);
  482.                 }
  483.                 Operation azioneCorrelata = new Operation();
  484.                 azioneCorrelata.setNome(nomeAzioneCorrelata);
  485.                 azioneCorrelata.setProfAzione(CostantiRegistroServizi.PROFILO_AZIONE_RIDEFINITO);
  486.                 azioneCorrelata.setFiltroDuplicati(StatoFunzionalita.ABILITATO); // secondo le ultime linee guida
  487.                 if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_SIMMETRICO.equals(profiloCollaborazione))
  488.                     azioneCorrelata.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_SIMMETRICO);
  489.                 else if(ProfiloDiCollaborazioneType.EGOV_IT_SERVIZIO_ASINCRONO_ASIMMETRICO.equals(profiloCollaborazione))
  490.                     azioneCorrelata.setProfiloCollaborazione(CostantiRegistroServizi.ASINCRONO_ASIMMETRICO);
  491.                 if(nomeServizio!=null)
  492.                     azioneCorrelata.setCorrelataServizio(nomeServizio);
  493.                 azioneCorrelata.setCorrelata(nomeAzione);
  494.                 ptCorrelato.addAzione(azioneCorrelata);
  495.                
  496.                 servizi.put(servizio, ptCorrelato);
  497.             }
  498.         }
  499.        
  500.         if(servizi!=null && !servizi.isEmpty()) {
  501.             for (String pt : servizi.keySet()) {
  502.                 as.addPortType(servizi.get(pt));
  503.             }
  504.         }

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