RegistroOpenSPCoopUtilities.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.core.registry.wsdl;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.File;
  23. import java.util.ArrayList;
  24. import java.util.HashMap;
  25. import java.util.HashSet;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Set;

  29. import javax.wsdl.Import;

  30. import org.openspcoop2.core.id.IDAccordo;
  31. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  32. import org.openspcoop2.core.registry.Documento;
  33. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  34. import org.openspcoop2.core.registry.driver.DriverRegistroServiziException;
  35. import org.openspcoop2.core.registry.driver.IDAccordoFactory;
  36. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  37. import org.openspcoop2.utils.LoggerWrapperFactory;
  38. import org.openspcoop2.utils.id.IDUtilities;
  39. import org.openspcoop2.utils.wsdl.DefinitionWrapper;
  40. import org.openspcoop2.utils.wsdl.WSDLUtilities;
  41. import org.openspcoop2.utils.xml.PrettyPrintXMLUtils;
  42. import org.openspcoop2.utils.xml.XSDUtils;
  43. import org.slf4j.Logger;
  44. import org.w3c.dom.Document;
  45. import org.w3c.dom.Element;
  46. import org.w3c.dom.Node;

  47. /**
  48.  * Utilities per la gestione dei bean accordi di servizio di OpenSPCoop
  49.  *
  50.  *
  51.  * @author Poli Andrea (apoli@link.it)
  52.  * @author Burlon Tommaso (tommaso.burlon@link.it)
  53.  * @author $Author$
  54.  * @version $Rev$, $Date$
  55.  */

  56. public class RegistroOpenSPCoopUtilities {

  57.     private Logger logger = null;
  58.     private org.openspcoop2.message.xml.MessageXMLUtils xmlUtils = null;
  59.     private XSDUtils xsdUtils = null;
  60.     private WSDLUtilities wsdlUtilities = null;
  61.     private OpenSPCoop2MessageFactory messageFactory;
  62.    
  63.     // Factory
  64.     private IDAccordoFactory idAccordoFactory = IDAccordoFactory.getInstance();
  65.        
  66.    
  67.     public RegistroOpenSPCoopUtilities(OpenSPCoop2MessageFactory messageFactory, Logger log){
  68.         if(log!=null)
  69.             this.logger = log;
  70.         else
  71.             this.logger = LoggerWrapperFactory.getLogger(RegistroOpenSPCoopUtilities.class);
  72.        
  73.         this.messageFactory = messageFactory;
  74.         this.xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.getInstance(this.messageFactory);
  75.         this.xsdUtils = new XSDUtils(this.xmlUtils);
  76.         this.wsdlUtilities = WSDLUtilities.getInstance(this.xmlUtils);
  77.     }
  78.    
  79.    
  80.    
  81.     /**
  82.      * Costruisce un Definition a partire da un accordo di servizio parte comune e eventualmente dai bytes del wsdl implementativo
  83.      *
  84.      * @param parteComune
  85.      * @param implementativoByte
  86.      * @param implementativoErogatore
  87.      * @return javax.wsdl.Definition
  88.      * @throws DriverRegistroServiziException
  89.      */
  90.     public javax.wsdl.Definition buildWsdlFromObjects(AccordoServizioParteComune parteComune, byte[] implementativoByte, boolean implementativoErogatore) throws DriverRegistroServiziException{
  91.         try{
  92.            
  93.             // Normalizzo l'accordo di servizio per avere i path relativi basati sul Registro dei Servizi di OpenSPCoop
  94.             AccordoServizioParteComune parteComuneNormalizzata = (AccordoServizioParteComune) parteComune.clone();
  95.             this.updateLocation(parteComuneNormalizzata, false, false);
  96.            
  97.             // Seleziona wsdl logico in base all'erogatore o fruitore
  98.             byte[] logicoByte = null;
  99.             if(implementativoErogatore){
  100.                 if(parteComuneNormalizzata.getByteWsdlLogicoErogatore()!=null){
  101.                     logicoByte = parteComuneNormalizzata.getByteWsdlLogicoErogatore();
  102.                 }else{
  103.                     throw new DriverRegistroServiziException("Byte del WSDL logico erogatore non presenti");
  104.                 }
  105.             }else{
  106.                 if(parteComuneNormalizzata.getByteWsdlLogicoFruitore()!=null){
  107.                     logicoByte = parteComuneNormalizzata.getByteWsdlLogicoFruitore();
  108.                 }else{
  109.                     throw new DriverRegistroServiziException("Byte del WSDL logico fruitore non presenti");
  110.                 }
  111.             }
  112.            
  113.             // Riporto in document il wsdl logico contenente gli import
  114.             com.ibm.wsdl.xml.WSDLReaderImpl builderWSDL = new com.ibm.wsdl.xml.WSDLReaderImpl();
  115.             javax.wsdl.Definition wsdl = null;
  116.             if(logicoByte==null){
  117.                 throw new Exception("Wsdl logico (byte[]) non definito");
  118.             }
  119.             this.logger.debug("Leggo WSDL logico");
  120.             Document documentLogico = this.xmlUtils.newDocument(logicoByte);

  121.            
  122.                            
  123.             // Gestione import presenti nel wsdl logico
  124.             Element wsdlElement = documentLogico.getDocumentElement();
  125.             String prefix = wsdlElement.getPrefix();
  126.             ByteArrayOutputStream xsd = new ByteArrayOutputStream();
  127.             HashMap<String,String> prefixForWSDL = new HashMap<>();
  128.                        
  129.            
  130.            
  131.             // NOTA: itero due volte per dare la possibilità al metodo  wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl chiamato da risoluzioneImportIncludeInXSD di poter riferire correttamente tutti gli schemi
  132.             //       via via regitrati in prefixForWSDL
  133.             //       Altrimenti l'ordine ne determina il funzionamento
  134.            
  135.             for (int k = 0; k < 2; k++) {
  136.                        
  137.                 boolean firstIteration = (k==0);
  138.                
  139.                 // NOTA: Avendo normalizzato il wsdl, tutti gli import/include sono dentro i types
  140.                
  141.                 List<Node> importIntoWSDL = this.wsdlUtilities.readImportsSchemaIntoTypes(documentLogico);
  142.                 //System.out.println("IMPORTS ["+importIntoWSDL.size()+"]");
  143.                 for(int i=0; i<importIntoWSDL.size(); i++){
  144.                     Node n = importIntoWSDL.get(i);
  145.                     //System.out.println("************************************* IMPORT *******************************************************************");
  146.                     /*String targetNamespaceXSD =  null;
  147.                     Object o = n.getUserData("TargetNamespaceSchema");
  148.                     if(o!=null){
  149.                         targetNamespaceXSD = (String)o;
  150.                     }*/
  151.                     //NON DEVO PRENDERE QUELLO DELLO SCHEMA MA QUELLO DEL XSD
  152.                     String namespaceImport = null;
  153.                     try{
  154.                         namespaceImport = this.xsdUtils.getImportNamespace(n);
  155.                     }catch(Exception e){
  156.                         // ignore
  157.                     }
  158.                     //System.out.println("TargetNamespace schema xsd che contiene l'import: "+targetNamespaceXSD);
  159.                     String location = null;
  160.                     try{
  161.                         location = this.xsdUtils.getImportSchemaLocation(n);
  162.                     }catch(Exception e){
  163.                         // ignore
  164.                     }
  165.                     //System.out.println("Import WSDL ["+namespaceImport+"] ["+location+"]");
  166.                     if(location!=null){
  167.                         //System.out.println("IMPORT XSD INTO WSDL!");
  168.                         if(CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD.equals(location)){
  169.                             if(parteComuneNormalizzata.getByteWsdlDefinitorio()!=null){
  170.                                 //System.out.println("DA WSDL AGGIUNGO WSDL DEFINITORIO");
  171.                                 xsd.write("\n".getBytes());
  172.                                 risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getByteWsdlDefinitorio(),
  173.                                         xsd, wsdlElement,prefixForWSDL, true, namespaceImport);
  174.                             }
  175.                         }
  176.                         else if(location.startsWith(CostantiRegistroServizi.ALLEGATI_DIR)){
  177.                             for(int j=0; j<parteComuneNormalizzata.sizeAllegatoList(); j++){
  178.                                 Documento allegato = parteComuneNormalizzata.getAllegato(j);
  179.                                 String file = CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+allegato.getFile();
  180.                                 //System.out.println("Check allegato.. ["+location+"]==["+file+"]");
  181.                                 if(location.equals(file)){
  182.                                     //System.out.println("DA WSDL AGGIUNGO ALLEGATO");
  183.                                     xsd.write("\n".getBytes());
  184.                                     risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getAllegato(j).getByteContenuto(),
  185.                                             xsd, wsdlElement,prefixForWSDL, true, namespaceImport);
  186.                                     break;
  187.                                 }
  188.                             }
  189.                         }
  190.                         else if(location.startsWith(CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR)){
  191.                             for(int j=0; j<parteComuneNormalizzata.sizeSpecificaSemiformaleList(); j++){
  192.                                 Documento specificaSemiformale = parteComuneNormalizzata.getSpecificaSemiformale(j);
  193.                                 String file = CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+specificaSemiformale.getFile();
  194.                                 //System.out.println("Check specifica.. ["+location+"]==["+file+"]");
  195.                                 if(location.equals(file)){
  196.                                     //System.out.println("DA WSDL AGGIUNGO SPECIFICA SEMIFORMALE");
  197.                                     xsd.write("\n".getBytes());
  198.                                     risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getSpecificaSemiformale(j).getByteContenuto(),
  199.                                             xsd, wsdlElement,prefixForWSDL, true, namespaceImport);
  200.                                     break;
  201.                                 }
  202.                             }
  203.                         }
  204.                     }
  205.                     //System.out.println("*******************************************  IMPORT  *************************************************************");
  206.                 }
  207.                
  208.                
  209.                 // NOTA: Avendo normalizzato il wsdl, tutti gli import/include sono dentro i types
  210.                
  211.                 List<Node> includeIntoWSDL = this.wsdlUtilities.readIncludesSchemaIntoTypes(documentLogico);
  212.                 //System.out.println("INCLUDE ["+includeIntoWSDL.size()+"]");
  213.                 for(int i=0; i<includeIntoWSDL.size(); i++){
  214.                     Node n = includeIntoWSDL.get(i);
  215.                     //System.out.println("************************************* INCLUDE *******************************************************************");
  216.                     Object o = n.getUserData("TargetNamespaceSchema");
  217.                     String targetNamespaceXSD =  null;
  218.                     if(o!=null){
  219.                         targetNamespaceXSD = (String)o;
  220.                     }
  221.                     //System.out.println("TargetNamespace schema xsd che contiene l'include: "+targetNamespaceXSD);
  222.                     String location = null;
  223.                     try{
  224.                         location = this.xsdUtils.getIncludeSchemaLocation(n);
  225.                     }catch(Exception e){
  226.                         // ignore
  227.                     }
  228.                     //System.out.println("Include WSDL ["+location+"]");
  229.                     if(location!=null){
  230.                         //System.out.println("IMPORT XSD INTO WSDL!");
  231.                         if(CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD.equals(location)){
  232.                             if(parteComuneNormalizzata.getByteWsdlDefinitorio()!=null){
  233.                                 //System.out.println("DA WSDL AGGIUNGO WSDL DEFINITORIO");
  234.                                 xsd.write("\n".getBytes());
  235.                                 risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getByteWsdlDefinitorio(),
  236.                                         xsd, wsdlElement,prefixForWSDL, false, targetNamespaceXSD);
  237.                             }
  238.                         }
  239.                         else if(location.startsWith(CostantiRegistroServizi.ALLEGATI_DIR)){
  240.                             for(int j=0; j<parteComuneNormalizzata.sizeAllegatoList(); j++){
  241.                                 Documento allegato = parteComuneNormalizzata.getAllegato(j);
  242.                                 String file = CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+allegato.getFile();
  243.                                 //System.out.println("Check allegato.. ["+location+"]==["+file+"]");
  244.                                 if(location.equals(file)){
  245.                                     //System.out.println("DA WSDL AGGIUNGO ALLEGATO");
  246.                                     xsd.write("\n".getBytes());
  247.                                     risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getAllegato(j).getByteContenuto(),
  248.                                             xsd, wsdlElement,prefixForWSDL, false, targetNamespaceXSD);
  249.                                     break;
  250.                                 }
  251.                             }
  252.                         }
  253.                         else if(location.startsWith(CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR)){
  254.                             for(int j=0; j<parteComuneNormalizzata.sizeSpecificaSemiformaleList(); j++){
  255.                                 Documento specificaSemiformale = parteComuneNormalizzata.getSpecificaSemiformale(j);
  256.                                 String file = CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+specificaSemiformale.getFile();
  257.                                 //System.out.println("Check specifica.. ["+location+"]==["+file+"]");
  258.                                 if(location.equals(file)){
  259.                                     //System.out.println("DA WSDL AGGIUNGO SPECIFICA SEMIFORMALE");
  260.                                     xsd.write("\n".getBytes());
  261.                                     risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getSpecificaSemiformale(j).getByteContenuto(),
  262.                                             xsd, wsdlElement,prefixForWSDL, false, targetNamespaceXSD);
  263.                                     break;
  264.                                 }
  265.                             }
  266.                         }
  267.                     }
  268.                     //System.out.println("*******************************************  INCLUDE  *************************************************************");
  269.                 }
  270.             }
  271.                        
  272.             if(this.wsdlUtilities.existsTypes(documentLogico)){
  273.                 //System.out.println("Rimozione Schemi from types");
  274.                
  275.                 // NOTA: Non è possibile lasciare gli schemi interni perche contengono include ed import
  276.                 // Inizialmente venivano rimossi solo gli schemi
  277.                 // Se però non è abilitata l'opzione dalla console che estra gli schemi da dentro il wsdl,
  278.                 // poi il wsdl non conteneva tutti gli schemi una volta effettuata questa normalizzazione
  279.                 // non venivano re-inseriti gli schemi definiti dentro il wsdl stesso
  280.                 //this.wsdlUtilities.removeSchemiIntoTypes(documentLogico);
  281.                
  282.                 List<Node> schemi = this.wsdlUtilities.getSchemiXSD(documentLogico);
  283.                 if(schemi!=null && schemi.size()>0){
  284.                     // Gli import ed includes sono già stati gestiti precedentemente
  285.                     for (Node schema : schemi) {
  286.                         boolean schemaWithOnlyImportOrIncludes = this.xsdUtils.isSchemaWithOnlyImportsAndIncludes(schema);
  287.                         if(schemaWithOnlyImportOrIncludes){
  288.                             this.wsdlUtilities.getIfExistsTypesElementIntoWSDL(documentLogico).removeChild(schema);
  289.                         }
  290.                         else{
  291.                             // Elimino import e include
  292.                             List<Node> nl = this.xsdUtils.readImportsAndIncludes(schema);
  293.                             if(nl!=null){
  294.                                 for (Node importInclude : nl) {
  295.                                     schema.removeChild(importInclude);
  296.                                 }
  297.                             }
  298.                         }
  299.                     }
  300.                 }
  301.                
  302.             }
  303.             else{
  304.                 //System.out.println("Add Empty types");    
  305.                 this.wsdlUtilities.addEmptyTypesIfNotExists(documentLogico);
  306.             }
  307.                                
  308.             // Costruisco wsdl logico che non contiene piu' gli import
  309.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  310.             bout.write(this.xmlUtils.toByteArray(documentLogico));
  311.             bout.flush();
  312.             bout.close();
  313.                        
  314.             // Calcolo keyword
  315.             String typesStart = null;
  316.             String typesClosed = null;
  317.             String typesEnd = null;
  318.             String definitionLine = null;
  319.             if(prefix!=null){
  320.                 typesStart = "<"+prefix+":types>";
  321.                 typesClosed = "<"+prefix+":types/>";
  322.                 typesEnd = "</"+prefix+":types>";
  323.                 definitionLine = "<"+prefix+":definitions ";
  324.             }else{
  325.                 typesStart = "<types>";
  326.                 typesClosed = "<types/>";
  327.                 typesEnd = "</types>";
  328.                 definitionLine = "<definitions ";
  329.             }
  330.            
  331.             //System.out.println("KEYWORD typesLine1["+typesStart+"] typesLine2["+typesClosed+"] definitionLine["+definitionLine+"]");
  332.            
  333.             // Aggiungo dentro types gli schemi trovati nelle precedenti analisi degli import
  334.             String wsdlTrasformato = bout.toString();
  335.             if(wsdlTrasformato.contains(typesStart)){
  336.                 //System.out.println("REPLACE1");
  337.                 wsdlTrasformato = wsdlTrasformato.replace(typesStart, typesStart+"\n"+xsd.toString());
  338.             }
  339.             else{
  340.                 //System.out.println("REPLACE2 contains("+wsdlTrasformato.contains(typesClosed)+")");
  341.                 wsdlTrasformato = wsdlTrasformato.replace(typesClosed, typesStart+"\n"+xsd.toString()+"\n\t"+typesEnd);
  342.             }
  343.            
  344.             // Elimino <?xml
  345.             if(wsdlTrasformato.contains("<?xml") ){
  346.                 //System.out.println("XML INSTR");
  347.                 int indexOf = wsdlTrasformato.indexOf("<?xml");
  348.                 int endIndexOf = wsdlTrasformato.indexOf(">",indexOf+"<?xml".length());
  349.                 //System.out.println("XML INSTR indexOf["+indexOf+"] endIndexOf["+endIndexOf+"]");
  350.                 if(endIndexOf>0 && indexOf>=0){
  351.                     if(indexOf>0){
  352.                         //System.out.println("XML INSTR A");
  353.                         wsdlTrasformato = wsdlTrasformato.substring(0, indexOf)+wsdlTrasformato.substring(endIndexOf+1);
  354.                     }
  355.                     else{
  356.                         //System.out.println("XML INSTR B");
  357.                         wsdlTrasformato = wsdlTrasformato.substring(endIndexOf+1);
  358.                     }
  359.                 }
  360.             }
  361.            
  362.             // Aggiunto prefissi al wsdl
  363.             Iterator<String> keys = prefixForWSDL.keySet().iterator();
  364.             while(keys.hasNext()){
  365.                 String key = keys.next();
  366.                 //System.out.println("ADD ["+key+"] ["+prefixForWSDL.get(key)+"]");
  367.                 wsdlTrasformato = wsdlTrasformato.replaceFirst(definitionLine, definitionLine+key+"=\""+prefixForWSDL.get(key)+"\" ");
  368.             }
  369.            
  370. //          File f = File.createTempFile("testErrore", ".tmp");
  371. //          org.openspcoop2.utils.resources.FileSystemUtilities.writeFile(f, wsdlTrasformato.getBytes());
  372. //          System.out.println("TEST PERCHE SCHIANTA ["+f.getAbsolutePath()+"] ["+wsdlTrasformato+"]");
  373.            
  374.             // Costruisco wsdl logico contenente gli schemi
  375.             documentLogico = this.xmlUtils.newDocument(wsdlTrasformato.getBytes());
  376.             this.logger.debug("Costruisco WSDL Logico per la seconda volta, stavolta con i types corretti");
  377.             wsdl = builderWSDL.readWSDL(null,documentLogico);
  378.            
  379.            
  380.             // Aggiungo parte Implementativa
  381.             if(implementativoByte!=null){
  382.                
  383.                 this.logger.debug("Leggo WSDL implementativo");
  384.                 Document documentImplementativo = this.xmlUtils.newDocument(implementativoByte);
  385.                
  386.                 this.logger.debug("Rimuovo import da WSDL Loimplementativogico");
  387.                 this.wsdlUtilities.removeImports(documentImplementativo);
  388.                 this.wsdlUtilities.removeTypes(documentImplementativo);
  389.                
  390.                 this.logger.debug("Costruisco WSDL Implementativo");
  391.                 javax.wsdl.Definition wsdlImplementativo = builderWSDL.readWSDL(null,documentImplementativo);
  392.                
  393.                 this.addParteImplementativa(wsdl, wsdlImplementativo);
  394.             }
  395.            
  396.             return wsdl;
  397.            
  398.         }catch (Exception e) {
  399.             throw new DriverRegistroServiziException("Riscontrato errore durante la costruzione del wsdl dai bytes: "+e.getMessage(),e);
  400.         }
  401.     }
  402.    
  403.    
  404.     /**
  405.      * Imposta correttamente le location degli imports nell'accordo di servizio parte comune
  406.      *
  407.      * @param accordoServizioOpenspcoop
  408.      * @param strutturaPackageCNIPA
  409.      * @param prettyDocument
  410.      * @throws DriverRegistroServiziException
  411.      */
  412.     public void updateLocation(org.openspcoop2.core.registry.AccordoServizioParteComune accordoServizioOpenspcoop,boolean strutturaPackageCNIPA, boolean prettyDocument) throws DriverRegistroServiziException{
  413.         try{
  414.             // WSDL
  415.             byte[]wsdlDefinitorio = accordoServizioOpenspcoop.getByteWsdlDefinitorio();
  416.             byte[]wsdlConcettuale = accordoServizioOpenspcoop.getByteWsdlConcettuale();
  417.             byte[]wsdlLogicoErogatore = accordoServizioOpenspcoop.getByteWsdlLogicoErogatore();
  418.             byte[]wsdlLogicoFruitore = accordoServizioOpenspcoop.getByteWsdlLogicoFruitore();
  419.            
  420.             // Associazione TargetNamespace a path dei files.
  421.             // Associazione path dei files per risoluzione include:
  422.             // - nome del file singolo
  423.             // - nome del file con il parent.
  424.             HashMap<String, String> targetNamespacesXSD = new HashMap<>();
  425.             HashMap<String, String> includePath = new HashMap<>();
  426.             if(wsdlDefinitorio!=null){
  427.                 String file = CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD;
  428.                 if(strutturaPackageCNIPA){
  429.                     file = ".."+File.separatorChar+CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+file;
  430.                 }
  431.                 // Associazione TargetNamespace a path dei files.
  432.                 String targetNamespace = null;
  433.                 try{
  434.                     targetNamespace = this.xsdUtils.getTargetNamespace(wsdlDefinitorio);
  435.                 }catch(Exception e){
  436.                     // ignore
  437.                 }
  438.                 if(targetNamespace!=null){
  439.                     //System.out.println("TARGET["+targetNamespace+"] FILE["+file+"]");
  440.                     targetNamespacesXSD.put(targetNamespace,file);
  441.                 }else{
  442.                     this.logger.debug("Target namespace non trovato per il wsdl definitorio ["+CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD+"]");
  443.                 }
  444.                 // Associazione path dei files per risoluzione include
  445.                 includePath.put(CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD, file);
  446.                 includePath.put(CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD, file);
  447.             }else{
  448.                 this.logger.debug("Bytes non presenti per il wsdl definitorio ["+CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD+"]");
  449.             }
  450.             for(int i=0; i<accordoServizioOpenspcoop.sizeAllegatoList();i++){
  451.                 Documento doc = accordoServizioOpenspcoop.getAllegato(i);
  452.                 File fLocalName = new File(doc.getFile());
  453.                 String file = CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+fLocalName.getName();
  454.                 if(strutturaPackageCNIPA){
  455.                     file = ".."+File.separatorChar+file;
  456.                 }
  457.                
  458.                 //System.out.println("UPDATE LOCATION ALLEGATO["+file+"]");
  459.                
  460.                 // Associazione TargetNamespace a path dei files.
  461.                 if(doc.getByteContenuto()!=null){
  462.                     String targetNamespace = null;
  463.                     try{
  464.                         targetNamespace = this.xsdUtils.getTargetNamespace(doc.getByteContenuto()); // verifico che sia un xsd
  465.                     }catch(Exception e){
  466.                         // ignore
  467.                     }
  468.                     if(targetNamespace==null){
  469.                         try{
  470.                             targetNamespace = this.wsdlUtilities.getTargetNamespace(doc.getByteContenuto()); // verifico che sia un wsdl
  471.                         }catch(Exception e){
  472.                             // ignore
  473.                         }
  474.                     }
  475.                     //System.out.println("TARGET NAMESPACE["+targetNamespace+"]");
  476.                     if(targetNamespace!=null){
  477.                         //System.out.println("TARGET["+targetNamespace+"] FILE["+file+"]");
  478.                         targetNamespacesXSD.put(targetNamespace,file);
  479.                     }else{
  480.                         this.logger.debug("Target namespace non trovato per l'allegato ["+doc.getFile()+"] (tipo:"+doc.getTipo()+")");
  481.                     }
  482.                 }else{
  483.                     this.logger.debug("Bytes non presenti per l'allegato ["+doc.getFile()+"] (tipo:"+doc.getTipo()+")");
  484.                 }
  485.                 // Associazione path dei files per risoluzione include
  486.                 includePath.put(fLocalName.getName(), file);
  487.                 includePath.put(CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+fLocalName.getName(), file);
  488.             }
  489.             for(int i=0; i<accordoServizioOpenspcoop.sizeSpecificaSemiformaleList();i++){
  490.                 Documento doc = accordoServizioOpenspcoop.getSpecificaSemiformale(i);
  491.                 File fLocalName = new File(doc.getFile());
  492.                 String file = CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+fLocalName.getName();
  493.                 if(strutturaPackageCNIPA){
  494.                     file = ".."+File.separatorChar+file;
  495.                 }
  496.                 // Associazione TargetNamespace a path dei files.
  497.                 if(doc.getByteContenuto()!=null){
  498.                     String targetNamespace = null;
  499.                     try{
  500.                         targetNamespace = this.xsdUtils.getTargetNamespace(doc.getByteContenuto()); // verifico che sia un xsd
  501.                     }catch(Exception e){
  502.                         // ignore
  503.                     }
  504.                     if(targetNamespace==null){
  505.                         try{
  506.                             targetNamespace = this.wsdlUtilities.getTargetNamespace(doc.getByteContenuto()); // verifico che sia un wsdl
  507.                         }catch(Exception e){
  508.                             // ignore
  509.                         }
  510.                     }
  511.                     if(targetNamespace!=null){
  512.                         //System.out.println("TARGET["+targetNamespace+"] FILE["+file+"]");
  513.                         targetNamespacesXSD.put(targetNamespace,file);
  514.                     }else{
  515.                         this.logger.debug("Target namespace non trovato per la specifica semiformale ["+doc.getFile()+"] (tipo:"+doc.getTipo()+")");
  516.                     }
  517.                 }else{
  518.                     this.logger.debug("Bytes non presenti per la specifica semiformale ["+doc.getFile()+"] (tipo:"+doc.getTipo()+")");
  519.                 }
  520.                 // Associazione path dei files per risoluzione include
  521.                 includePath.put(fLocalName.getName(), file);
  522.                 includePath.put(CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+fLocalName.getName(), file);
  523.             }
  524.            
  525.             // WSDL
  526.             if(wsdlConcettuale!=null){
  527.                 this.logger.debug("Update Wsdl Concettuale...");
  528.                 wsdlConcettuale = updateImportsAndIncludesWSDLLocation("WSDLConcettuale",wsdlConcettuale,targetNamespacesXSD,includePath,prettyDocument,true);
  529.                 accordoServizioOpenspcoop.setByteWsdlConcettuale(wsdlConcettuale);
  530.                 this.logger.debug("Update Wsdl Concettuale ok");
  531.             }
  532.             if(wsdlLogicoErogatore!=null){
  533.                 this.logger.debug("Update Wsdl Logico Erogatore...");
  534.                 wsdlLogicoErogatore = updateImportsAndIncludesWSDLLocation("WSDLLogicoErogatore",wsdlLogicoErogatore,targetNamespacesXSD,includePath,prettyDocument,true);
  535.                 accordoServizioOpenspcoop.setByteWsdlLogicoErogatore(wsdlLogicoErogatore);
  536.                 this.logger.debug("Update Wsdl Logico Erogatore ok");
  537.             }
  538.             if(wsdlLogicoFruitore!=null){
  539.                 this.logger.debug("Update Wsdl Logico Fruitore...");
  540.                 wsdlLogicoFruitore = updateImportsAndIncludesWSDLLocation("WSDLLogicoFruitore",wsdlLogicoFruitore,targetNamespacesXSD,includePath,prettyDocument,true);
  541.                 accordoServizioOpenspcoop.setByteWsdlLogicoFruitore(wsdlLogicoFruitore);
  542.                 this.logger.debug("Update Wsdl Logico Fruitore ok");
  543.             }

  544.             // XSD
  545.             if(wsdlDefinitorio!=null){
  546.                 this.logger.debug("Update Wsdl Definitorio (import)...");
  547.                 wsdlDefinitorio = updateImportXSDLocation(wsdlDefinitorio,targetNamespacesXSD,prettyDocument);
  548.                 this.logger.debug("Update Wsdl Definitorio (include)...");
  549.                 wsdlDefinitorio = updateIncludeXSDLocation(wsdlDefinitorio,includePath,prettyDocument);
  550.                 this.logger.debug("Update Wsdl Definitorio ok");
  551.                 accordoServizioOpenspcoop.setByteWsdlDefinitorio(wsdlDefinitorio);
  552.             }
  553.             for(int i=0; i<accordoServizioOpenspcoop.sizeAllegatoList();i++){
  554.                 Documento doc = accordoServizioOpenspcoop.getAllegato(i);
  555.                 if(doc.getByteContenuto()!=null){
  556.                     this.logger.debug("Update Allegato di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] (import)...");
  557.                     byte [] allegato = updateImportXSDLocation(doc.getByteContenuto(),targetNamespacesXSD,prettyDocument);
  558.                     if(allegato!=null){
  559.                         this.logger.debug("Update Allegato di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] (include)...");
  560.                         allegato = updateIncludeXSDLocation(allegato,includePath,prettyDocument);
  561.                         if(allegato!=null){
  562.                             doc.setByteContenuto(allegato);
  563.                             this.logger.debug("Update Allegato di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] ok");
  564.                         }else{
  565.                             this.logger.debug("Update (include) Allegato di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] non effettuato, il documento non e' uno schema XSD");
  566.                         }
  567.                     }else{
  568.                         this.logger.debug("Update (import) Allegato di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] non effettuato, il documento non e' uno schema XSD");
  569.                     }
  570.                 }
  571.             }
  572.             for(int i=0; i<accordoServizioOpenspcoop.sizeSpecificaSemiformaleList();i++){
  573.                 Documento doc = accordoServizioOpenspcoop.getSpecificaSemiformale(i);
  574.                 if(doc.getByteContenuto()!=null){
  575.                     this.logger.debug("Update SpecificaSemiformale di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] (import)...");
  576.                     byte [] specificaSemiformale = updateImportXSDLocation(doc.getByteContenuto(),targetNamespacesXSD,prettyDocument);
  577.                     if(specificaSemiformale!=null){
  578.                         this.logger.debug("Update SpecificaSemiformale di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] (include)...");
  579.                         specificaSemiformale = updateIncludeXSDLocation(specificaSemiformale,includePath,prettyDocument);
  580.                         if(specificaSemiformale!=null){
  581.                             doc.setByteContenuto(specificaSemiformale);
  582.                             this.logger.debug("Update SpecificaSemiformale di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] ok");
  583.                         }else{
  584.                             this.logger.debug("Update (include) SpecificaSemiformale di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] non effettuato, il documento non e' uno schema XSD");
  585.                         }
  586.                     }else{
  587.                         this.logger.debug("Update (import)SpecificaSemiformale di tipo ["+doc.getTipo()+"] ["+doc.getFile()+"] non effettuato, il documento non e' uno schema XSD");
  588.                     }
  589.                 }
  590.             }
  591.            
  592.            
  593.         }catch(Exception e){
  594.             this.logger.error("Correzione import non riuscita: "+e.getMessage(),e);
  595.            
  596.             throw new DriverRegistroServiziException("Riscontrato errore durante la lettura del wsdl: "+e.getMessage(),e);
  597.         }
  598.     }
  599.    
  600.     /**
  601.      * Imposta correttamente le location degli imports nell'accordo di servizio parte specifica
  602.      *
  603.      * @param servizioOpenspcoop
  604.      * @param strutturaPackageCNIPA
  605.      * @param prettyDocument
  606.      * @throws DriverRegistroServiziException
  607.      */
  608.     public void updateLocation(org.openspcoop2.core.registry.AccordoServizioParteSpecifica servizioOpenspcoop,boolean strutturaPackageCNIPA, boolean prettyDocument) throws DriverRegistroServiziException{
  609.         try{
  610.             // WSDL
  611.             byte[]wsdlImplementativoErogatore = servizioOpenspcoop.getByteWsdlImplementativoErogatore();
  612.             byte[]wsdlImplementativoFruitore = servizioOpenspcoop.getByteWsdlImplementativoFruitore();
  613.            
  614.             HashMap<String, String> targetNamespacesXSD = new HashMap<>();
  615.             IDAccordo idAccordoParteComune = this.idAccordoFactory.getIDAccordoFromUri(servizioOpenspcoop.getAccordoServizioParteComune());        
  616.            
  617.             if(wsdlImplementativoErogatore!=null){
  618.                 String targetNamespace = this.wsdlUtilities.getTargetNamespace(wsdlImplementativoErogatore);
  619.                 if(targetNamespace!=null){
  620.                     //System.out.println("TARGET["+targetNamespace+"] FILE["+file+"]");
  621.                     String file = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL;
  622.                     if(strutturaPackageCNIPA){
  623.                         file = ".."+File.separatorChar+".."+File.separatorChar+idAccordoParteComune.getNome()+File.separatorChar+CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR+File.separatorChar+file;
  624.                     }
  625.                     targetNamespacesXSD.put(targetNamespace,file);
  626.                 }else{
  627.                     this.logger.debug("Target namespace non trovato per il wsdl implementativo erogatore ["+CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL+"]");
  628.                 }
  629.                
  630.                 this.logger.debug("Update Wsdl Implementativo Erogatore...");
  631.                 wsdlImplementativoErogatore = updateImportsAndIncludesWSDLLocation("WSDLImplementativoErogatore",wsdlImplementativoErogatore,targetNamespacesXSD,null,prettyDocument,false);
  632.                 servizioOpenspcoop.setByteWsdlImplementativoErogatore(wsdlImplementativoErogatore);
  633.                 this.logger.debug("Update Wsdl Implementativo Erogatore ok");
  634.             }
  635.             if(wsdlImplementativoFruitore!=null){
  636.                 String targetNamespace = this.wsdlUtilities.getTargetNamespace(wsdlImplementativoFruitore);
  637.                 if(targetNamespace!=null){
  638.                     //System.out.println("TARGET["+targetNamespace+"] FILE["+file+"]");
  639.                     String file = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL;
  640.                     if(strutturaPackageCNIPA){
  641.                         file = ".."+File.separatorChar+".."+File.separatorChar+idAccordoParteComune.getNome()+File.separatorChar+CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR+File.separatorChar+file;
  642.                     }
  643.                     targetNamespacesXSD.put(targetNamespace,file);
  644.                 }else{
  645.                     this.logger.debug("Target namespace non trovato per il wsdl implementativo fruitore ["+CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL+"]");
  646.                 }
  647.                
  648.                 this.logger.debug("Update Wsdl Implementativo Fruitore...");
  649.                 wsdlImplementativoFruitore = updateImportsAndIncludesWSDLLocation("WSDLImplementativoFruitore",wsdlImplementativoFruitore,targetNamespacesXSD,null,prettyDocument,false);
  650.                 servizioOpenspcoop.setByteWsdlImplementativoFruitore(wsdlImplementativoFruitore);
  651.                 this.logger.debug("Update Wsdl Implementativo Fruitore ok");
  652.             }
  653.            
  654.            
  655.         }catch(Exception e){
  656.             this.logger.error("Correzione import non riuscita: "+e.getMessage(),e);
  657.             throw new DriverRegistroServiziException("Riscontrato errore durante la lettura del wsdl: "+e.getMessage(),e);
  658.         }
  659.     }
  660.    
  661.    
  662.    
  663.    
  664.    
  665.    
  666.    
  667.     /* ************ UTILITY **************** */
  668.    
  669.     public byte[] eliminaASParteComune(byte[] wsdlBytes,boolean implementativoErogatore) throws DriverRegistroServiziException{
  670.        
  671.         try{
  672.        
  673.             Document d = this.xmlUtils.newDocument(wsdlBytes);
  674.             this.wsdlUtilities.removeTypes(d);
  675.             this.wsdlUtilities.removeImports(d);
  676.                    
  677.             DefinitionWrapper wsdl = new DefinitionWrapper(d,this.xmlUtils);
  678.                
  679.             wsdl.createTypes();
  680.             Import importLogico = wsdl.createImport();
  681.             if(implementativoErogatore){
  682.                 importLogico.setLocationURI(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL);
  683.             }
  684.             else{
  685.                 importLogico.setLocationURI(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL);
  686.             }
  687.             importLogico.setNamespaceURI(this.wsdlUtilities.getTargetNamespace(wsdlBytes));
  688.             wsdl.addImport(importLogico);
  689.            
  690.             wsdl.removeAllMessages();
  691.             wsdl.removeAllPortTypes();
  692.            
  693.             //System.out.println(wsdl.toString());
  694.    
  695.             // serializzo wsdl
  696.             byte[] wsdlSenzaParteComune = wsdl.toByteArray();          
  697.             return wsdlSenzaParteComune;
  698.            
  699.         }catch(Exception e){
  700.             this.logger.error("Eliminazione  ASParteComune non riuscita: "+e.getMessage(),e);
  701.             throw new DriverRegistroServiziException("Riscontrato errore durante l'eliminazione dell'ASParteComune del wsdl: "+e.getMessage(),e);
  702.         }
  703.     }
  704.    
  705.     public byte[] aggiungiImportASParteComune(byte[] wsdlBytes,boolean implementativoErogatore) throws DriverRegistroServiziException{
  706.        
  707.         try{
  708.        
  709.             Document d = this.xmlUtils.newDocument(wsdlBytes);
  710.             this.wsdlUtilities.removeTypes(d);
  711.             this.wsdlUtilities.removeImports(d);
  712.            
  713.             DefinitionWrapper wsdl = new DefinitionWrapper(d,this.xmlUtils);
  714.            
  715.             wsdl.createTypes();
  716.             Import importLogico = wsdl.createImport();
  717.             if(implementativoErogatore){
  718.                 importLogico.setLocationURI(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL);
  719.             }
  720.             else{
  721.                 importLogico.setLocationURI(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL);
  722.             }
  723.             importLogico.setNamespaceURI(this.wsdlUtilities.getTargetNamespace(wsdlBytes));
  724.             wsdl.addImport(importLogico);
  725.            
  726.             return wsdl.toByteArray();
  727.            
  728.         }catch(Exception e){
  729.             this.logger.error("aggiungiImportASParteComune non riuscito: "+e.getMessage(),e);
  730.             throw new DriverRegistroServiziException("Riscontrato errore durante l'eliminazione dell'ASParteComune del wsdl: "+e.getMessage(),e);
  731.         }
  732.        
  733.     }
  734.    
  735.     public byte[] eliminaImportASParteComune(byte[] wsdlBytes) throws DriverRegistroServiziException{
  736.        
  737.         try{
  738.        
  739.             Document d = this.xmlUtils.newDocument(wsdlBytes);
  740.             this.wsdlUtilities.removeTypes(d);
  741.             this.wsdlUtilities.removeImports(d);
  742.            
  743.             DefinitionWrapper wsdl = new DefinitionWrapper(d,this.xmlUtils);
  744.             return wsdl.toByteArray();
  745.            
  746.         }catch(Exception e){
  747.             this.logger.error("Eliminazione  ASParteComune non riuscita: "+e.getMessage(),e);
  748.             throw new DriverRegistroServiziException("Riscontrato errore durante l'eliminazione dell'ASParteComune del wsdl: "+e.getMessage(),e);
  749.         }
  750.        
  751.     }
  752.    
  753.     /**
  754.      * Aggiunge i bindings/services di un wsdl implementativo in un wsdl logico.
  755.      *
  756.      * @param wsdlOriginale
  757.      * @param wsdlImplementativo
  758.      */
  759.     public void addParteImplementativa(javax.wsdl.Definition wsdlOriginale,javax.wsdl.Definition wsdlImplementativo){
  760.         this.logger.debug("Aggiungo wsdl-binding...");
  761.         java.util.Map<?,?> bindings = wsdlImplementativo.getAllBindings();
  762.         if(bindings!=null && bindings.size()>0){
  763.             this.logger.debug("Aggiungo wsdl-binding ["+bindings.size()+"] a wsdl ritornato");
  764.             java.util.Iterator<?> bindingsIterator = bindings.values().iterator();
  765.             while(bindingsIterator.hasNext()) {
  766.                 javax.wsdl.Binding bindingWSDL = (javax.wsdl.Binding) bindingsIterator.next();
  767.                 wsdlOriginale.addBinding(bindingWSDL);
  768.             }
  769.         }
  770.        
  771.         this.logger.debug("Aggiungo wsdl-service...");
  772.         java.util.Map<?,?> services = wsdlImplementativo.getAllServices();
  773.         if(services!=null && services.size()>0){
  774.             this.logger.debug("Aggiungo wsdl-service ["+services.size()+"] a wsdl ritornato");
  775.             java.util.Iterator<?> servicesIterator = services.values().iterator();
  776.             while(servicesIterator.hasNext()) {
  777.                 javax.wsdl.Service serviceWSDL = (javax.wsdl.Service) servicesIterator.next();
  778.                 wsdlOriginale.addService(serviceWSDL);
  779.             }
  780.         }
  781.     }
  782.    
  783.    
  784.    
  785.    
  786.    
  787.    
  788.    
  789.    
  790.    
  791.    
  792.     /* ---------------- METODI PRIVATI ------------------------- */
  793.    
  794.     /** Risoluzione import include */
  795.     private void risoluzioneImportIncludeInXSD(boolean firstIteration, AccordoServizioParteComune parteComuneNormalizzata,byte[] documentXSD,ByteArrayOutputStream xsd,
  796.             Element wsdlElement,HashMap<String,String> prefixForWSDL,boolean docImportato,String targetNamespaceParent)throws DriverRegistroServiziException{
  797.         risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, documentXSD, xsd,
  798.                  wsdlElement, prefixForWSDL, docImportato, targetNamespaceParent, new HashSet<>(), 1);
  799.        
  800.     }
  801.     /** Risoluzione import include */
  802.     private void risoluzioneImportIncludeInXSD(boolean firstIteration, AccordoServizioParteComune parteComuneNormalizzata,byte[] documentXSD,ByteArrayOutputStream xsd,
  803.             Element wsdlElement,HashMap<String,String> prefixForWSDL,boolean docImportato,String targetNamespaceParent,Set<String> observedLocations, int profondita)throws DriverRegistroServiziException{
  804.         try{
  805.            
  806.             //System.out.println("\n\n===============================================");
  807.            
  808.             Document doc = this.xmlUtils.newDocument(documentXSD);
  809.             Element docElement = doc.getDocumentElement();
  810.             String targetNamespace = null;
  811.            
  812.             // controllo che non venga importato il namespace xml di default con un prefix diverso da "xml"
  813.             if (this.xsdUtils.isXSDSchema(doc)) {
  814.                 targetNamespace = this.xsdUtils.getTargetNamespace(doc);
  815.                 if (targetNamespace != null && targetNamespace.equals("http://www.w3.org/XML/1998/namespace"))
  816.                     return;
  817.             }
  818.            
  819.             //System.out.println("Risoluzione dei prefissi .....");
  820.             // Risoluzione prefix da inserire nel wsdl ed eliminazione attributi negli schemi
  821.             String uniquePrefix = "_p"+profondita+"_n"+IDUtilities.getUniqueSerialNumber("risoluzioneImportIncludeInXSD")+"_";
  822.             targetNamespace = this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(docElement, wsdlElement, prefixForWSDL, uniquePrefix, docImportato, targetNamespaceParent);
  823.            
  824.             // Risoluzione ricorsiva degli import presenti nel xsd
  825.             List<Node> importIntoXSD = this.xsdUtils.readImports(doc);
  826.             for(int i=0; i<importIntoXSD.size(); i++){
  827.                 Node n = importIntoXSD.get(i);
  828.                 //System.out.println("----------------------------------- IMPORT ("+profondita+")------------------------------------------------------------------------");
  829.                 String location = null;
  830.                 try{
  831.                     location = this.xsdUtils.getImportSchemaLocation(n);
  832.                 }catch(Exception e){
  833.                     // ignore
  834.                 }
  835.                
  836.                 if (observedLocations.contains(location))
  837.                     continue;
  838.                 //System.out.println("Import XSD ["+this.wsdlUtilities.getAttributeValue(n,"namespace")+"] ["+location+"]");
  839.                 //System.out.println("IMPORT ["+location+"]");
  840.                 if(location!=null && location.startsWith(CostantiRegistroServizi.ALLEGATI_DIR)){
  841.                     for(int j=0; j<parteComuneNormalizzata.sizeAllegatoList(); j++){
  842.                         Documento allegato = parteComuneNormalizzata.getAllegato(j);
  843.                         String file = CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+allegato.getFile();
  844.                         //System.out.println("Check allegato.. ["+location+"]==["+file+"]");
  845.                         if(location.equals(file)){
  846.                             //System.out.println("AGGIUNGO ALLEGATO INTERNO");
  847.                             xsd.write("\n".getBytes());
  848.                             observedLocations.add(location);
  849.                             risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getAllegato(j).getByteContenuto(),
  850.                                     xsd, wsdlElement,prefixForWSDL, true, targetNamespace, observedLocations, (profondita+1));
  851.                             break;
  852.                         }
  853.                     }
  854.                 }
  855.                 else if(location!=null && location.startsWith(CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR)){
  856.                     for(int j=0; j<parteComuneNormalizzata.sizeSpecificaSemiformaleList(); j++){
  857.                         Documento specificaSemiformale = parteComuneNormalizzata.getSpecificaSemiformale(j);
  858.                         String file = CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+specificaSemiformale.getFile();
  859.                         //System.out.println("Check specifica.. ["+location+"]==["+file+"]");
  860.                         if(location.equals(file)){
  861.                             //System.out.println("AGGIUNGO SPECIFICA SEMIFORMALE");
  862.                             xsd.write("\n".getBytes());
  863.                             observedLocations.add(location);
  864.                             risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getSpecificaSemiformale(j).getByteContenuto(),
  865.                                     xsd, wsdlElement,prefixForWSDL, true, targetNamespace, observedLocations, (profondita+1));
  866.                             break;
  867.                         }
  868.                     }
  869.                 }
  870.                 //System.out.println("--------------------------------------------- FINE IMPORT ("+profondita+")--------------------------------------------------------------");
  871.             }
  872.                
  873.            
  874.            
  875.            
  876.             // Risoluzione ricorsiva degli include presenti nel xsd
  877.             List<Node> includeIntoXSD = this.xsdUtils.readIncludes(doc);
  878.             for(int i=0; i<includeIntoXSD.size(); i++){
  879.                 Node n = includeIntoXSD.get(i);
  880.                 //System.out.println("----------------------------------- INCLUDE ("+profondita+")------------------------------------------------------------------------");
  881.                 String location = null;
  882.                 try{
  883.                     location = this.xsdUtils.getIncludeSchemaLocation(n);
  884.                 }catch(Exception e){
  885.                     // ignore
  886.                 }
  887.                
  888.                 if (observedLocations.contains(location))
  889.                     continue;
  890.                 //System.out.println("Include XSD ["+this.wsdlUtilities.getAttributeValue(n,"namespace")+"] ["+location+"]");
  891.                 //System.out.println("INCLUDE ["+location+"]");
  892.                 if(location!=null && location.startsWith(CostantiRegistroServizi.ALLEGATI_DIR)){
  893.                     for(int j=0; j<parteComuneNormalizzata.sizeAllegatoList(); j++){
  894.                         Documento allegato = parteComuneNormalizzata.getAllegato(j);
  895.                         String file = CostantiRegistroServizi.ALLEGATI_DIR+File.separatorChar+allegato.getFile();
  896.                         //System.out.println("Check allegato.. ["+location+"]==["+file+"]");
  897.                         if(location.equals(file)){
  898.                             //System.out.println("AGGIUNGO ALLEGATO INTERNO");
  899.                             xsd.write("\n".getBytes());
  900.                             observedLocations.add(location);
  901.                             risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getAllegato(j).getByteContenuto(),
  902.                                     xsd, wsdlElement,prefixForWSDL, false, targetNamespace, observedLocations, (profondita+1));
  903.                             break;
  904.                         }
  905.                     }
  906.                 }
  907.                 else if(location!=null && location.startsWith(CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR)){
  908.                     for(int j=0; j<parteComuneNormalizzata.sizeSpecificaSemiformaleList(); j++){
  909.                         Documento specificaSemiformale = parteComuneNormalizzata.getSpecificaSemiformale(j);
  910.                         String file = CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR+File.separatorChar+specificaSemiformale.getFile();
  911.                         //System.out.println("Check specifica.. ["+location+"]==["+file+"]");
  912.                         if(location.equals(file)){
  913.                             //System.out.println("AGGIUNGO SPECIFICA SEMIFORMALE");
  914.                             xsd.write("\n".getBytes());
  915.                             observedLocations.add(location);
  916.                             risoluzioneImportIncludeInXSD(firstIteration, parteComuneNormalizzata, parteComuneNormalizzata.getSpecificaSemiformale(j).getByteContenuto(),
  917.                                     xsd, wsdlElement,prefixForWSDL, false, targetNamespace, observedLocations, (profondita+1));
  918.                             break;
  919.                         }
  920.                     }
  921.                 }
  922.                 //System.out.println("----------------------------------- FINE INCLUDE ("+profondita+")------------------------------------------------------------------------");
  923.                
  924.             }
  925.            
  926.            
  927.             if(!firstIteration) {
  928.            
  929.                 // Rimuovo tutti gli import/include precedentemente aggiunti direttamente nel types del wsdl
  930.                 this.xsdUtils.removeImportsAndIncludes(doc);
  931.                
  932.                
  933.                
  934.                 // Rigenerazione byte[] del xsd trasformato
  935.                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  936.                 this.xmlUtils.writeTo(doc, bout, true);
  937.                 bout.flush();
  938.                 bout.close();
  939.                 //if(docImportato){
  940.                 //  System.out.println("AGGIUNGO XSD IMPORTATO ["+bout.toString()+"]");
  941.                 //}else{
  942.                 //System.out.println("AGGIUNGO XSD INCLUSO ["+bout.toString()+"]");
  943.                 //}
  944.                 xsd.write(bout.toByteArray());
  945.                
  946.             }
  947.            
  948.            
  949.            
  950.         }catch (Exception e) {
  951.             throw new DriverRegistroServiziException("Riscontrato errore durante la costruzione del xsd dai bytes: "+e.getMessage(),e);
  952.         }
  953.     }
  954.    
  955.     private byte [] updateImportsAndIncludesWSDLLocation(String file,byte [] wsdl,
  956.             HashMap<String, String> targetNamespacesXSD,HashMap<String, String> includePath,
  957.             boolean prettyDocument,boolean traduciImportIntoTypesImport) throws org.openspcoop2.utils.wsdl.WSDLException{
  958.        
  959.         try{
  960.        
  961.             //System.out.println("\n\n"+file);
  962.            
  963.             if(!this.xmlUtils.isDocument(wsdl)){
  964.                 throw new org.openspcoop2.utils.wsdl.WSDLException("WSDL["+file+"] non e' un documento valido");
  965.             }
  966.             Document doc = this.xmlUtils.newDocument(wsdl);
  967.            
  968.             // Read import into types.
  969.             List<Node> importsIntoTypesIntoWSDL = this.wsdlUtilities.readImportsSchemaIntoTypes(doc);
  970.             for(int i=0; i<importsIntoTypesIntoWSDL.size(); i++){
  971.                 Node n = importsIntoTypesIntoWSDL.get(i);
  972.                 //System.out.println("CLASS["+n.getClass().getName()+"]");
  973.                 String namespaceImport = null;
  974.                 try{
  975.                     namespaceImport = this.xsdUtils.getImportNamespace(n);
  976.                 }catch(Exception e){
  977.                     // ignore
  978.                 }
  979.                 //System.out.println("TargetNamespace schema xsd che contiene l'import: "+targetNamespaceXSD);
  980.                 String location = null;
  981.                 try{
  982.                     location = this.xsdUtils.getImportSchemaLocation(n);
  983.                 }catch(Exception e){
  984.                     // ignore
  985.                 }
  986.                 //System.out.println("Import WSDL ["+namespaceImport+"] ["+location+"]");
  987.                 if(namespaceImport!=null){
  988.                    
  989.                     String path = targetNamespacesXSD.get(namespaceImport);
  990.                     if(path==null){
  991.                         this.logger.debug("Schema non trovato per il namespace "+namespaceImport);
  992.                     }
  993.                     else{
  994. //                      Node old = n.getAttributes().removeNamedItem("schemaLocation");
  995. //                      old.setNodeValue(path);
  996. //                      n.getAttributes().setNamedItem(old);
  997.                         this.xsdUtils.updateSchemaLocation(n, path);
  998.                         this.logger.debug("Reimpostata location: "+path);
  999.                     }
  1000.                    
  1001.                 }else{
  1002.                     this.logger.debug("Import presente nel WSDL["+file+"] ["+location+"] non possiede il target namespace");
  1003.                 }
  1004.             }
  1005.            
  1006.             // Read include into types.
  1007.             if(includePath!=null){
  1008.                 List<Node> includesIntoTypesIntoWSDL = this.wsdlUtilities.readIncludesSchemaIntoTypes(doc);
  1009.                 for(int i=0; i<includesIntoTypesIntoWSDL.size(); i++){
  1010.                     Node n = includesIntoTypesIntoWSDL.get(i);
  1011.                     //System.out.println("CLASS["+n.getClass().getName()+"]");
  1012.                     String location = null;
  1013.                     try{
  1014.                         location = this.xsdUtils.getIncludeSchemaLocation(n);
  1015.                     }catch(Exception e){
  1016.                         // ignore
  1017.                     }
  1018.                     //System.out.println("Include TYPES ["+this.wsdlUtilities.getAttributeValue(n,"namespace")+"] ["+location+"]");
  1019.                     if(location!=null){
  1020.                        
  1021.                         File locationF = new File(location);
  1022.                         String path = null;
  1023.                         if(locationF.getParentFile()!=null){
  1024.                             String key = locationF.getParentFile().getName()+File.separatorChar+locationF.getName();
  1025.                             //System.out.println("CERCO CON CHIAVE: "+key);
  1026.                             path = includePath.get(key);
  1027.                         }
  1028.                         if(path==null){
  1029.                             String key = locationF.getName();
  1030.                             //System.out.println("CERCO CON CHIAVE: "+key);
  1031.                             path = includePath.get(key);
  1032.                         }
  1033.                         if(path==null){
  1034.                             //System.out.println("NON TROVATO PER: "+location);
  1035.                             this.logger.debug("Schema non trovato per la location "+location);
  1036.                         }
  1037.                         else{
  1038.                             //System.out.println("TROVATO: "+path);
  1039. //                          Node old = n.getAttributes().removeNamedItem("schemaLocation");
  1040. //                          old.setNodeValue(path);
  1041. //                          n.getAttributes().setNamedItem(old);
  1042.                             this.xsdUtils.updateSchemaLocation(n, path);
  1043.                             this.logger.debug("Reimpostata location: "+path);
  1044.                         }
  1045.                        
  1046.                     }else{
  1047.                         this.logger.debug("Include presente nel XSD ["+location+"] non possiede la location?");
  1048.                     }
  1049.                 }
  1050.             }
  1051.            
  1052.             // Read import into wsdl.
  1053.             List<Node> importsIntoWSDL = this.wsdlUtilities.readImports(doc);
  1054.             List<Node> newSchemi = new ArrayList<Node>();      
  1055.             for(int i=0; i<importsIntoWSDL.size(); i++){
  1056.                 Node n = importsIntoWSDL.get(i);
  1057.                 String namespaceImport = null;
  1058.                 try{
  1059.                     namespaceImport = this.wsdlUtilities.getImportNamespace(n);
  1060.                 }catch(Exception e){
  1061.                     // ignore
  1062.                 }
  1063.                 //System.out.println("TargetNamespace schema xsd che contiene l'import: "+targetNamespaceXSD);
  1064.                 String location = null;
  1065.                 try{
  1066.                     location = this.wsdlUtilities.getImportLocation(n);
  1067.                 }catch(Exception e){
  1068.                     // ignore
  1069.                 }
  1070.                 //System.out.println("Import NORMALE ["+namespaceImport+"] ["+location+"]");
  1071.                 if(namespaceImport!=null){
  1072.                    
  1073.                     String path = targetNamespacesXSD.get(namespaceImport);
  1074.                     if(path==null){
  1075.                         this.logger.debug("Schema non trovato per il namespace "+namespaceImport);
  1076.                     }
  1077.                     else{
  1078.                         if(traduciImportIntoTypesImport){
  1079.                             //System.out.println("CREO SCHEMA!!!!");
  1080.                             Element schemaElement = doc.createElementNS("http://www.w3.org/2001/XMLSchema","schema");
  1081.                             schemaElement.setPrefix("xsd");
  1082.                             schemaElement.setAttribute("targetNamespace",this.wsdlUtilities.getTargetNamespace(wsdl));
  1083.                             //schemaElement.setAttribute("xmlns:xsd","http://www.w3.org/2001/XMLSchema"); se si decommenta questo, viene aggiunto due volte l'import?
  1084.                             Element importElement = doc.createElementNS("http://www.w3.org/2001/XMLSchema","import");
  1085.                             importElement.setPrefix("xsd");
  1086.                             importElement.setAttribute("schemaLocation",path);
  1087.                             importElement.setAttribute("namespace",namespaceImport);
  1088.                             schemaElement.appendChild(importElement);
  1089.                             newSchemi.add(schemaElement);
  1090.                         }
  1091.                         else{
  1092. //                          Node old = n.getAttributes().removeNamedItem("location");
  1093. //                          old.setNodeValue(path);
  1094. //                          n.getAttributes().setNamedItem(old);
  1095.                             this.wsdlUtilities.updateLocation(n, path);
  1096.                             this.logger.debug("Reimpostata location: "+path);
  1097.                         }
  1098.                     }
  1099.                    
  1100.                 }else{
  1101.                     this.logger.debug("Import presente nel WSDL["+file+"] ["+location+"] non possiede il target namespace");
  1102.                 }
  1103.             }
  1104.             //System.out.println("RIMUOVO TUTTI GLI IMPORT DIRETTI SUL WSDL");
  1105.             if(traduciImportIntoTypesImport){
  1106.                 this.wsdlUtilities.removeImports(doc);
  1107.             }
  1108.            
  1109.             if(newSchemi.size()>0){
  1110.                 Node types = this.wsdlUtilities.getIfExistsTypesElementIntoWSDL(doc);
  1111.                 if(types==null){
  1112.                     //System.out.println("NULL??");
  1113.                     Node definition = this.wsdlUtilities.getIfExistsDefinitionsElementIntoWSDL(doc);
  1114.                     if(definition==null){
  1115.                         this.logger.debug("Definition non esistente");
  1116.                     }else{
  1117.                         types = this.wsdlUtilities.addEmptyTypesIfNotExists(doc);
  1118.                         for(int i=0; i<newSchemi.size(); i++){
  1119.                             this.wsdlUtilities.addSchemaIntoTypes(doc, newSchemi.get(i));
  1120.                             //System.out.println("APPENDO SCHEMA DOPO CREO");
  1121.                         }
  1122.                     }
  1123.                 }else{
  1124.                     for(int i=0; i<newSchemi.size(); i++){
  1125.                         //System.out.println("APPENDO SCHEMA");
  1126.                         this.wsdlUtilities.addSchemaIntoTypes(doc, newSchemi.get(i));
  1127.                     }
  1128.                 }
  1129.             }
  1130.            
  1131.    
  1132.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1133.             if(prettyDocument){
  1134.                 //XMLUtils.PrettyDocumentToStream(doc, bout);
  1135.                 PrettyPrintXMLUtils.prettyPrintWithTrAX(doc, bout);
  1136.             }else{
  1137.                 this.xmlUtils.writeTo(doc, bout);
  1138.             }
  1139.             bout.flush();
  1140.             bout.close();
  1141.             return bout.toByteArray();
  1142.            
  1143.         }catch(Exception e){
  1144.             throw new org.openspcoop2.utils.wsdl.WSDLException(e.getMessage(),e);
  1145.         }
  1146.     }
  1147.    
  1148.     private byte [] updateImportXSDLocation(byte [] xsd,HashMap<String, String> targetNamespacesXSD, boolean prettyDocument) throws org.openspcoop2.utils.wsdl.WSDLException{
  1149.        
  1150.         try{
  1151.        
  1152.             if(!this.xmlUtils.isDocument(xsd)){
  1153.                 return null;
  1154.             }
  1155.             Document doc = this.xmlUtils.newDocument(xsd);
  1156.                
  1157.             List<Node> importsIntoXSD = this.xsdUtils.readImports(doc);
  1158.             for(int i=0; i<importsIntoXSD.size(); i++){
  1159.                 Node n = importsIntoXSD.get(i);
  1160.                 String namespaceImport = null;
  1161.                 try{
  1162.                     namespaceImport = this.xsdUtils.getImportNamespace(n);
  1163.                 }catch(Exception e){
  1164.                     // ignore
  1165.                 }
  1166.                 //System.out.println("TargetNamespace schema xsd che contiene l'import: "+targetNamespaceXSD);
  1167.                 String location = null;
  1168.                 try{
  1169.                     location = this.xsdUtils.getImportSchemaLocation(n);
  1170.                 }catch(Exception e){
  1171.                     // ignore
  1172.                 }
  1173.                 //System.out.println("Import ["+namespaceImport+"] ["+location+"]");
  1174.                 if(namespaceImport!=null && location!=null){
  1175.                     // Lo schema location non è presente ad esempio quando si costruisce un unico file wsdl+xsd,
  1176.                     // e tutti gli xsd sono all'interno del wsdl. E' presente l'import ma non lo schema location
  1177.            
  1178.                     String path = targetNamespacesXSD.get(namespaceImport);
  1179.                     if(path==null){
  1180.                         this.logger.debug("Schema non trovato per il namespace "+namespaceImport);
  1181.                     }
  1182.                     else{
  1183. //                      Node old = n.getAttributes().removeNamedItem("schemaLocation");
  1184. //                      old.setNodeValue(path);
  1185. //                      n.getAttributes().setNamedItem(old);
  1186.                         this.xsdUtils.updateSchemaLocation(n, path);
  1187.                         this.logger.debug("Reimpostata location: "+path);
  1188.                     }
  1189.                    
  1190.                 }else{
  1191.                     this.logger.debug("Import presente nel XSD ["+location+"] non possiede il target namespace");
  1192.                 }
  1193.             }
  1194.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1195.             if(prettyDocument){
  1196.                 //XMLUtils.PrettyDocumentToStream(doc, bout);
  1197.                 PrettyPrintXMLUtils.prettyPrintWithTrAX(doc, bout);
  1198.             }else{
  1199.                 this.xmlUtils.writeTo(doc, bout);
  1200.             }
  1201.             bout.flush();
  1202.             bout.close();
  1203.             return bout.toByteArray();
  1204.            
  1205.         }catch(Exception e){
  1206.             throw new org.openspcoop2.utils.wsdl.WSDLException(e.getMessage(),e);
  1207.         }
  1208.     }

  1209.     private byte [] updateIncludeXSDLocation(byte [] xsd,HashMap<String, String> includePath, boolean prettyDocument) throws org.openspcoop2.utils.wsdl.WSDLException{
  1210.        
  1211.         try{
  1212.        
  1213.             if(!this.xmlUtils.isDocument(xsd)){
  1214.                 return null;
  1215.             }
  1216.             Document doc = this.xmlUtils.newDocument(xsd);
  1217.                
  1218.             List<Node> includeIntoXSD = this.xsdUtils.readIncludes(doc);
  1219.             for(int i=0; i<includeIntoXSD.size(); i++){
  1220.                 Node n = includeIntoXSD.get(i);
  1221.                 String location = null;
  1222.                 try{
  1223.                     location = this.xsdUtils.getIncludeSchemaLocation(n);
  1224.                 }catch(Exception e){
  1225.                     // ignore
  1226.                 }
  1227.                 //System.out.println("Include ["+location+"]");
  1228.                 if(location!=null){
  1229.                    
  1230.                     File locationF = new File(location);
  1231.                     String path = null;
  1232.                     if(locationF.getParentFile()!=null){
  1233.                         String key = locationF.getParentFile().getName()+File.separatorChar+locationF.getName();
  1234.                         //System.out.println("CERCO CON CHIAVE: "+key);
  1235.                         path = includePath.get(key);
  1236.                     }
  1237.                     if(path==null){
  1238.                         String key = locationF.getName();
  1239.                         //System.out.println("CERCO CON CHIAVE: "+key);
  1240.                         path = includePath.get(key);
  1241.                     }
  1242.                     if(path==null){
  1243.                         this.logger.debug("Schema non trovato per la location "+location);
  1244.                     }
  1245.                     else{
  1246.                         //System.out.println("TROVATO");
  1247. //                      Node old = n.getAttributes().removeNamedItem("schemaLocation");
  1248. //                      old.setNodeValue(path);
  1249. //                      n.getAttributes().setNamedItem(old);
  1250.                         this.xsdUtils.updateSchemaLocation(n, path);
  1251.                         this.logger.debug("Reimpostata location: "+path);
  1252.                     }
  1253.                    
  1254.                 }else{
  1255.                     this.logger.debug("Include presente nel XSD ["+location+"] non possiede la location?");
  1256.                 }
  1257.             }
  1258.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1259.             if(prettyDocument){
  1260.                 //XMLUtils.PrettyDocumentToStream(doc, bout);
  1261.                 PrettyPrintXMLUtils.prettyPrintWithTrAX(doc, bout);
  1262.             }else{
  1263.                 this.xmlUtils.writeTo(doc, bout);
  1264.             }
  1265.             bout.flush();
  1266.             bout.close();
  1267.             return bout.toByteArray();
  1268.            
  1269.         }catch(Exception e){
  1270.             throw new org.openspcoop2.utils.wsdl.WSDLException(e.getMessage(),e);
  1271.         }
  1272.     }
  1273. }