StandardWSDL.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.io.IOException;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Map;

  29. import javax.wsdl.Binding;
  30. import javax.wsdl.Import;
  31. import javax.wsdl.Message;
  32. import javax.wsdl.PortType;
  33. import javax.wsdl.Service;
  34. import javax.wsdl.Types;
  35. import javax.wsdl.WSDLException;
  36. import javax.wsdl.extensions.schema.Schema;
  37. import javax.xml.namespace.QName;
  38. import javax.xml.parsers.ParserConfigurationException;
  39. import javax.xml.transform.TransformerException;

  40. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  41. import org.openspcoop2.utils.id.IDUtilities;
  42. import org.openspcoop2.utils.resources.FileSystemUtilities;
  43. import org.openspcoop2.utils.wsdl.DefinitionWrapper;
  44. import org.openspcoop2.utils.wsdl.WSDLUtilities;
  45. import org.openspcoop2.utils.xml.SchemaXSD;
  46. import org.openspcoop2.utils.xml.XMLException;
  47. import org.openspcoop2.utils.xml.XSDUtils;
  48. import org.w3c.dom.Document;
  49. import org.w3c.dom.Element;
  50. import org.w3c.dom.Node;
  51. import org.w3c.dom.NodeList;
  52. import org.xml.sax.SAXException;

  53. import com.ibm.wsdl.ImportImpl;
  54. import com.ibm.wsdl.TypesImpl;
  55. import com.ibm.wsdl.extensions.schema.SchemaImpl;


  56. /**
  57.  * Classe che gestisce la creazione dei wsdl standard a partire da WSDL suddivisi in schemi, parte comune e parte specifica
  58.  *
  59.  * @author Lorenzo Nardi (nardi@link.it)
  60.  * @author $Author$
  61.  * @version $Rev$, $Date$
  62.  *
  63.  */

  64. public class StandardWSDL {
  65.    
  66.    
  67.     /* ------- INPUT --------- */
  68.     private DefinitionWrapper implementativoErogatore = null, implementativoFruitore = null;
  69.     private DefinitionWrapper logicoErogatore = null, logicoFruitore = null;
  70.     private StandardWSDLOutputMode outputMode = StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI;
  71.     private String pathImplementativo, pathLogico;
  72.    
  73.    
  74.     /* ------- OUTPUT --------- */
  75.     private DefinitionWrapper wsdlErogatore = null, wsdlFruitore = null, wsdlUnificato = null;
  76.     private List<SchemaXSDAccordoServizio> schemiWsdlErogatore = new ArrayList<SchemaXSDAccordoServizio>();
  77.     private List<SchemaXSDAccordoServizio> schemiWsdlFruitore = new ArrayList<SchemaXSDAccordoServizio>();
  78.     private List<SchemaXSDAccordoServizio> schemiWsdlUnificato = new ArrayList<SchemaXSDAccordoServizio>();
  79.    
  80.     /* ------- ALTRO ---------- */
  81.     private org.openspcoop2.message.xml.MessageXMLUtils xmlUtils = null;
  82.     private XSDUtils xsdUtils = null;
  83.     private WSDLUtilities wsdlUtilities = null;
  84.    
  85.    
  86.     /* ------- Costruttori --------- */
  87.    
  88.     public StandardWSDL (String implementativoErogatorePath, String implementativoFruitorePath, StandardWSDLOutputMode outputMode) throws WSDLException, StandardWSDLException, IOException, ParserConfigurationException, SAXException, XMLException{
  89.        
  90.         this.xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;
  91.         this.xsdUtils = new XSDUtils(this.xmlUtils);
  92.         this.wsdlUtilities = WSDLUtilities.getInstance(this.xmlUtils);
  93.        
  94.         // Vincolo i due documenti (se specificati entrambi) ad essere nel solito folder
  95.         this.pathImplementativo = getParentFile(implementativoErogatorePath);
  96.         if(implementativoFruitorePath != null){
  97.             String fileFruitoreParent = getParentFile(implementativoFruitorePath);
  98.             if(this.pathImplementativo!=null){
  99.                 if(fileFruitoreParent==null){
  100.                     throw new StandardWSDLException("Fruitore ed Erogatore in folder differenti non sono supportati da questo tool");
  101.                 }
  102.                 if(this.pathImplementativo.compareTo(fileFruitoreParent) != 0){
  103.                     throw new StandardWSDLException("Fruitore ed Erogatore in folder differenti non sono supportati da questo tool");
  104.                 }
  105.             }
  106.         }
  107.        
  108.         this.implementativoErogatore = new DefinitionWrapper(implementativoErogatorePath,this.xmlUtils);
  109.         if(implementativoFruitorePath != null){
  110.             this.implementativoFruitore = new DefinitionWrapper(implementativoFruitorePath,this.xmlUtils);
  111.         }
  112.        
  113.         this.outputMode = outputMode;
  114.        
  115.         setup(false,null, null);
  116.     }
  117.    
  118.    
  119.     public StandardWSDL (List<SchemaXSDAccordoServizio> schemi, byte[] logicoErogatore, byte[] implementativoErogatore, byte[] logicoFruitore, byte[] implementativoFruitore,
  120.             StandardWSDLOutputMode outputMode) throws WSDLException, StandardWSDLException, IOException, ParserConfigurationException, SAXException, org.openspcoop2.utils.wsdl.WSDLException, XMLException{
  121.         this(schemi, logicoErogatore, implementativoErogatore, schemi, logicoFruitore, implementativoFruitore,outputMode);
  122.     }

  123.     public StandardWSDL (List<SchemaXSDAccordoServizio> schemiErogatore, byte[] logicoErogatore, byte[] implementativoErogatore,
  124.             List<SchemaXSDAccordoServizio> schemiFruitore, byte[] logicoFruitore, byte[] implementativoFruitore,
  125.             StandardWSDLOutputMode outputMode) throws WSDLException, StandardWSDLException, IOException, ParserConfigurationException, SAXException, org.openspcoop2.utils.wsdl.WSDLException, XMLException{
  126.        
  127.         this.xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;
  128.         this.xsdUtils = new XSDUtils(this.xmlUtils);
  129.         this.wsdlUtilities = WSDLUtilities.getInstance(this.xmlUtils);
  130.        
  131.         if(StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL.equals(outputMode)==false &&
  132.                 StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI.equals(outputMode)==false){
  133.             throw new StandardWSDLException("OutputMode non permesso quando in input vengono forniti i byte[]");
  134.         }
  135.         this.outputMode = outputMode;
  136.                
  137.         // EROGATORE
  138.         if(logicoErogatore == null)
  139.             throw new StandardWSDLException("Logico erogatore deve essere specificato");
  140.         if(implementativoErogatore==null)
  141.             throw new StandardWSDLException("Implementativo erogatore deve essere specificato");
  142.                    
  143.         // implementativoErogatore
  144.         Document implementativoErogatoreDoc =  this.xmlUtils.newDocument(implementativoErogatore);
  145.         implementativoErogatoreDoc = cleanupWsdlImportsAndTypes(implementativoErogatoreDoc);
  146.         this.implementativoErogatore = new DefinitionWrapper(implementativoErogatoreDoc,this.xmlUtils);
  147.        
  148.         // logicoErogatore
  149.         Document logicoErogatoreDoc = this.xmlUtils.newDocument(logicoErogatore);
  150.         // lettura import per eventuali riaggiunte in outMode=MANTIENI_IMPORT_INCLUDE_ORIGINALI
  151.         List<Node> importPresentiWsdlLogicoErogatore = this.wsdlUtilities.readImports(logicoErogatoreDoc);
  152.         List<Node> importTypesPresentiWsdlLogicoErogatore = this.wsdlUtilities.readImportsSchemaIntoTypes(logicoErogatoreDoc);
  153.         List<Node> includeTypesPresentiWsdlLogicoErogatore = this.wsdlUtilities.readIncludesSchemaIntoTypes(logicoErogatoreDoc);
  154.         // genero wsdl object
  155.         logicoErogatoreDoc = cleanupWsdlImportsAndTypes(logicoErogatoreDoc);
  156.         this.logicoErogatore = new DefinitionWrapper(logicoErogatoreDoc,this.xmlUtils);
  157.         // riaggiungo imports/includes
  158.         this.addImportsAndTypesToWsdl(this.logicoErogatore, importPresentiWsdlLogicoErogatore,
  159.                 includeTypesPresentiWsdlLogicoErogatore, importTypesPresentiWsdlLogicoErogatore);

  160.        
  161.         // FRUITORE
  162.         if(implementativoFruitore != null){
  163.            
  164.             // implementativoFruitore
  165.             Document implementativoFruitoreDoc = this.xmlUtils.newDocument(implementativoFruitore);
  166.             implementativoFruitoreDoc = cleanupWsdlImportsAndTypes(implementativoFruitoreDoc);
  167.             this.implementativoFruitore = new DefinitionWrapper(implementativoFruitoreDoc,this.xmlUtils);
  168.            
  169.             // logicoFruitore
  170.             Document logicoFruitoreDoc = this.xmlUtils.newDocument(logicoFruitore);
  171.             // lettura import  per eventuali riaggiunte in outMode=MANTIENI_IMPORT_INCLUDE_ORIGINALI
  172.             List<Node> importPresentiWsdlLogicoFruitore = this.wsdlUtilities.readImports(logicoFruitoreDoc);
  173.             List<Node> importTypesPresentiWsdlLogicoFruitore = this.wsdlUtilities.readImportsSchemaIntoTypes(logicoFruitoreDoc);
  174.             List<Node> includeTypesPresentiWsdlLogicoFruitore = this.wsdlUtilities.readIncludesSchemaIntoTypes(logicoFruitoreDoc);
  175.             // genero wsdl object
  176.             logicoFruitoreDoc = cleanupWsdlImportsAndTypes(logicoFruitoreDoc);
  177.             this.logicoFruitore = new DefinitionWrapper(logicoFruitoreDoc,this.xmlUtils);
  178.             // riaggiungo imports/includes
  179.             this.addImportsAndTypesToWsdl(this.logicoFruitore, importPresentiWsdlLogicoFruitore,
  180.                     includeTypesPresentiWsdlLogicoFruitore, importTypesPresentiWsdlLogicoFruitore);
  181.            
  182.            
  183.             // ****** import/include per wsdl unificato *****
  184.             if(importPresentiWsdlLogicoErogatore!=null){
  185.                 for(int i=0;i<importPresentiWsdlLogicoFruitore.size();i++){
  186.                     Node n = importPresentiWsdlLogicoFruitore.get(i);
  187.                     boolean trovato = false;
  188.                     for(int j=0;j<importPresentiWsdlLogicoErogatore.size();j++){
  189.                         Node giaPresente = importPresentiWsdlLogicoErogatore.get(j);
  190.                         try{
  191.                             if(this.xmlUtils.toString(giaPresente).equals(this.xmlUtils.toString(n))){
  192.                                 trovato = true;
  193.                                 break;
  194.                             }
  195.                         }catch(Exception e){
  196.                             throw new StandardWSDLException(e.getMessage(),e);
  197.                         }
  198.                     }
  199.                     if(!trovato){
  200.                         importPresentiWsdlLogicoErogatore.add(n);
  201.                     }
  202.                 }
  203.             }else
  204.                 importPresentiWsdlLogicoErogatore = importPresentiWsdlLogicoFruitore;
  205.            
  206.             if(includeTypesPresentiWsdlLogicoErogatore!=null){
  207.                 for(int i=0;i<includeTypesPresentiWsdlLogicoFruitore.size();i++){
  208.                     Node n = includeTypesPresentiWsdlLogicoFruitore.get(i);
  209.                     boolean trovato = false;
  210.                     for(int j=0;j<includeTypesPresentiWsdlLogicoErogatore.size();j++){
  211.                         Node giaPresente = includeTypesPresentiWsdlLogicoErogatore.get(j);
  212.                         try{
  213.                             if(this.xmlUtils.toString(giaPresente).equals(this.xmlUtils.toString(n))){
  214.                                 trovato = true;
  215.                                 break;
  216.                             }
  217.                         }catch(Exception e){
  218.                             throw new StandardWSDLException(e.getMessage(),e);
  219.                         }
  220.                     }
  221.                     if(!trovato){
  222.                         includeTypesPresentiWsdlLogicoErogatore.add(n);
  223.                     }
  224.                 }
  225.             }else
  226.                 includeTypesPresentiWsdlLogicoErogatore = includeTypesPresentiWsdlLogicoFruitore;
  227.            
  228.             if(importTypesPresentiWsdlLogicoErogatore!=null){
  229.                 for(int i=0;i<importTypesPresentiWsdlLogicoFruitore.size();i++){
  230.                     Node n = importTypesPresentiWsdlLogicoFruitore.get(i);
  231.                     boolean trovato = false;
  232.                     for(int j=0;j<importTypesPresentiWsdlLogicoErogatore.size();j++){
  233.                         Node giaPresente = importTypesPresentiWsdlLogicoErogatore.get(j);
  234.                         try{
  235.                             if(this.xmlUtils.toString(giaPresente).equals(this.xmlUtils.toString(n))){
  236.                                 trovato = true;
  237.                                 break;
  238.                             }
  239.                         }catch(Exception e){
  240.                             throw new StandardWSDLException(e.getMessage(),e);
  241.                         }
  242.                     }
  243.                     if(!trovato){
  244.                         importTypesPresentiWsdlLogicoErogatore.add(n);
  245.                     }
  246.                 }
  247.             }else
  248.                 importTypesPresentiWsdlLogicoErogatore = importTypesPresentiWsdlLogicoFruitore;
  249.            
  250.         }
  251.        
  252.        
  253.         // UNIFICATO
  254.         this.wsdlUnificato = new DefinitionWrapper(logicoErogatoreDoc,this.xmlUtils);
  255.         this.addImportsAndTypesToWsdl(this.wsdlUnificato, importPresentiWsdlLogicoErogatore,
  256.                 includeTypesPresentiWsdlLogicoErogatore, importTypesPresentiWsdlLogicoErogatore);
  257.        
  258.        
  259.         setup(true,schemiErogatore, schemiFruitore);
  260.     }
  261.    
  262.     private void setup(boolean setupFromByte,List<SchemaXSDAccordoServizio> schemiErogatore, List<SchemaXSDAccordoServizio> schemiFruitore) throws StandardWSDLException, WSDLException, ParserConfigurationException, SAXException, IOException, XMLException{
  263.        
  264.         List<byte[]> schemiInglobareWsdlErogatore = null;
  265.         List<byte[]> schemiInglobareWsdlFruitore = null;
  266.        
  267.         HashMap<String,String> prefixForWSDLErogatore = new HashMap<>();
  268.         HashMap<String,String> prefixForWSDLFruitore = new HashMap<>();
  269.         String uniquePrefix = "_n"+IDUtilities.getUniqueSerialNumber("StandardWSDL.setup")+"_";
  270.        
  271.        
  272.         // ----- Generazione wsdl erogatore -----
  273.         // Il logico e' null, in caso il setupFromByte==false
  274.         this.wsdlErogatore = importLogico(this.implementativoErogatore, this.logicoErogatore, setupFromByte);  
  275.        
  276.         // ----- Gestione schemi wsdl erogatore -----
  277.         if(setupFromByte) {
  278.             // Schemi sono stati passati in input. Li devo solo salvare come output
  279.             if(schemiErogatore!=null && schemiErogatore.size()>0){
  280.                
  281.                 if(StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL.equals(this.outputMode)){
  282.                     // StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL
  283.                     try{
  284.                         schemiInglobareWsdlErogatore = gestioneSchemiInBaseOutputMode_inputByteArray(true, schemiErogatore, prefixForWSDLErogatore, uniquePrefix);
  285.                     }catch(Exception e){
  286.                         throw new StandardWSDLException(e.getMessage(),e);
  287.                     }
  288.                 }
  289.                 else{
  290.                     // StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI
  291.                     this.schemiWsdlErogatore.addAll(schemiErogatore);
  292.                 }
  293.                
  294.             }
  295.         }
  296.         else{
  297.             // Schemi vengono letti dal wsdl
  298.             try{
  299.                 schemiInglobareWsdlErogatore = gestioneSchemiInBaseOutputMode_inputWsdl(true);
  300.             }catch(Exception e){
  301.                 throw new StandardWSDLException(e.getMessage(),e);
  302.             }
  303.         }
  304.        
  305.         if(this.implementativoFruitore!=null){
  306.            
  307.             // ----- Generazione wsdl fruitore -----
  308.             // Il logico e' null, in caso il setupFromByte==false
  309.             this.wsdlFruitore = importLogico(this.implementativoFruitore, this.logicoFruitore, setupFromByte);
  310.            
  311.             // ----- Gestione schemi wsdl fruitore -----
  312.             if(setupFromByte) {
  313.                 // Schemi sono stati passati in input. Li devo solo salvare come output
  314.                
  315.                 if(StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL.equals(this.outputMode)){
  316.                     // StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL
  317.                     try{
  318.                         schemiInglobareWsdlFruitore = gestioneSchemiInBaseOutputMode_inputByteArray(false, schemiFruitore, prefixForWSDLFruitore, uniquePrefix);
  319.                     }catch(Exception e){
  320.                         throw new StandardWSDLException(e.getMessage(),e);
  321.                     }
  322.                 }
  323.                 else{
  324.                     // StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI
  325.                     this.schemiWsdlFruitore.addAll(schemiFruitore);
  326.                 }

  327.             }
  328.             else{
  329.                 // Schemi vengono letti dal wsdl
  330.                 try{
  331.                     schemiInglobareWsdlFruitore = gestioneSchemiInBaseOutputMode_inputWsdl(false);
  332.                 }catch(Exception e){
  333.                     throw new StandardWSDLException(e.getMessage(),e);
  334.                 }
  335.             }
  336.         }
  337.        
  338.         // Non riuscendo a clonare un wsdl (se portato in byte e ricreato, non funzionano gli imports)
  339.         // carico nell'unico il logicoErogatore e ci importo l'implementativo
  340.         this.wsdlUnificato = importLogico(this.implementativoErogatore, this.wsdlUnificato, setupFromByte);
  341.         if(this.wsdlFruitore!=null){
  342.             this.wsdlUnificato = join(this.wsdlUnificato, this.wsdlFruitore);
  343.         }
  344.        
  345.        
  346.        
  347.         // add schemi
  348.         if(schemiInglobareWsdlErogatore!=null && schemiInglobareWsdlErogatore.size()>0){
  349.             this.wsdlErogatore = addSchemiWsdlTypes(this.wsdlErogatore, schemiInglobareWsdlErogatore);
  350.         }
  351.        
  352.         if(this.wsdlFruitore!=null){
  353.            
  354.             if(schemiInglobareWsdlFruitore!=null && schemiInglobareWsdlFruitore.size()>0)
  355.                 this.wsdlFruitore = addSchemiWsdlTypes(this.wsdlFruitore, schemiInglobareWsdlFruitore);
  356.            
  357.             if(schemiInglobareWsdlErogatore!=null && schemiInglobareWsdlErogatore.size()>0 &&
  358.                     schemiInglobareWsdlFruitore!=null && schemiInglobareWsdlFruitore.size()>0){
  359.                 this.wsdlUnificato = addSchemiWsdlTypes(this.wsdlUnificato, join(schemiInglobareWsdlErogatore, schemiInglobareWsdlFruitore));
  360.             }
  361.             else if(schemiInglobareWsdlErogatore!=null && schemiInglobareWsdlErogatore.size()>0){
  362.                 this.wsdlUnificato = addSchemiWsdlTypes(this.wsdlUnificato, schemiInglobareWsdlErogatore);
  363.             }
  364.             else if(schemiInglobareWsdlFruitore!=null && schemiInglobareWsdlFruitore.size()>0){
  365.                 this.wsdlUnificato = addSchemiWsdlTypes(this.wsdlUnificato, schemiInglobareWsdlFruitore);
  366.             }
  367.         }
  368.         else{
  369.             if(schemiInglobareWsdlErogatore!=null && schemiInglobareWsdlErogatore.size()>0){
  370.                 this.wsdlUnificato = addSchemiWsdlTypes(this.wsdlUnificato, schemiInglobareWsdlErogatore);
  371.             }
  372.         }
  373.        
  374.         if(this.schemiWsdlErogatore.size()>0)
  375.             this.schemiWsdlUnificato.addAll(this.schemiWsdlErogatore);
  376.         if(this.schemiWsdlFruitore.size()>0)
  377.             this.schemiWsdlUnificato.addAll(this.schemiWsdlFruitore);
  378.     }
  379.    
  380.    
  381.    
  382.    
  383.    
  384.    
  385.     /* ------------------ Metodi pubblici ----------------------- */
  386.    
  387.     public void writeWsdlErogatoreTo(String dir,boolean prettyPrint) throws StandardWSDLException{
  388.         this.writeWsdlErogatoreTo(new File(dir),prettyPrint);
  389.     }
  390.     public void writeWsdlErogatoreTo(File dir,boolean prettyPrint) throws StandardWSDLException{
  391.         try{
  392.             File wsdl = new File(dir,CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR+File.separatorChar+"Erogatore.wsdl");
  393.             FileSystemUtilities.mkdirParentDirectory(wsdl);
  394.             this.wsdlUtilities.writeWsdlTo(this.wsdlErogatore,wsdl,prettyPrint);
  395.             if(this.schemiWsdlErogatore.size()>0){
  396.                 for(int i=0; i<this.schemiWsdlErogatore.size(); i++){
  397.                     this.schemiWsdlErogatore.get(i).writeTo(dir,prettyPrint);
  398.                 }
  399.             }
  400.         }catch(Exception e){
  401.             throw new StandardWSDLException(e.getMessage(),e);
  402.         }
  403.     }
  404.    
  405.     public void writeWsdlFruitoreTo(String dir,boolean prettyPrint) throws StandardWSDLException{
  406.         this.writeWsdlFruitoreTo(new File(dir),prettyPrint);
  407.     }
  408.     public void writeWsdlFruitoreTo(File dir,boolean prettyPrint) throws StandardWSDLException{
  409.         try{
  410.             File wsdl = new File(dir,CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR+File.separatorChar+"Fruitore.wsdl");
  411.             FileSystemUtilities.mkdirParentDirectory(wsdl);
  412.             this.wsdlUtilities.writeWsdlTo(this.wsdlFruitore,wsdl,prettyPrint);
  413.             if(this.schemiWsdlFruitore.size()>0){
  414.                 for(int i=0; i<this.schemiWsdlFruitore.size(); i++){
  415.                     this.schemiWsdlFruitore.get(i).writeTo(dir,prettyPrint);
  416.                 }
  417.             }
  418.         }catch(Exception e){
  419.             throw new StandardWSDLException(e.getMessage(),e);
  420.         }
  421.     }
  422.    
  423.     public void writeWsdlUnificatoTo(String dir,boolean prettyPrint) throws StandardWSDLException{
  424.         this.writeWsdlUnificatoTo(new File(dir),prettyPrint);
  425.     }
  426.     public void writeWsdlUnificatoTo(File dir,boolean prettyPrint) throws StandardWSDLException{
  427.         try{
  428.             File wsdl = new File(dir,CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR+File.separatorChar+"Definition.wsdl");
  429.             FileSystemUtilities.mkdirParentDirectory(wsdl);
  430.             this.wsdlUtilities.writeWsdlTo(this.wsdlUnificato,wsdl,prettyPrint);
  431.             if(this.schemiWsdlUnificato.size()>0){
  432.                 for(int i=0; i<this.schemiWsdlUnificato.size(); i++){
  433.                     this.schemiWsdlUnificato.get(i).writeTo(dir,prettyPrint);
  434.                 }
  435.             }
  436.         }catch(Exception e){
  437.             throw new StandardWSDLException(e.getMessage(),e);
  438.         }
  439.     }
  440.    
  441.     public DefinitionWrapper getWsdlErogatore() {
  442.         return this.wsdlErogatore;
  443.     }
  444.     public DefinitionWrapper getWsdlFruitore() {
  445.         return this.wsdlFruitore;
  446.     }
  447.     public DefinitionWrapper getWsdlUnificato() {
  448.         return this.wsdlUnificato;
  449.     }
  450.    
  451.     public List<SchemaXSDAccordoServizio> getSchemiWsdlErogatore() {
  452.         return this.schemiWsdlErogatore;
  453.     }
  454.     public List<SchemaXSDAccordoServizio> getSchemiWsdlFruitore() {
  455.         return this.schemiWsdlFruitore;
  456.     }
  457.     public List<SchemaXSDAccordoServizio> getSchemiWsdlUnificato() {
  458.         return this.schemiWsdlUnificato;
  459.     }
  460.    
  461.    
  462.    
  463.    
  464.     /* -------------------- SCHEMI ----------------------------*/
  465.    
  466.     private List<byte[]> gestioneSchemiInBaseOutputMode_inputWsdl(boolean erogatore) throws StandardWSDLException{
  467.        
  468.         try{
  469.                    
  470.             // Trasformo definition in Document/Element
  471.             DefinitionWrapper wsdl = null;
  472.             if(erogatore){
  473.                 wsdl = this.wsdlErogatore;
  474.             }
  475.             else{
  476.                 wsdl = this.wsdlFruitore;
  477.             }
  478.             Document documentWSDL = this.xmlUtils.newDocument(wsdl.toByteArray());
  479.             Element wsdlElement = documentWSDL.getDocumentElement();
  480.             HashMap<String,String> prefixForWSDL = new HashMap<>();
  481.            
  482.             List<Node> schemiImportatiDalWsdl = new ArrayList<Node>();
  483.             List<Node> schemiInclusiDalWsdl = new ArrayList<Node>();
  484.            
  485.             // leggo dal wsdl
  486.             List<SchemaXSDAccordoServizio> listaSchemiImportati = new ArrayList<SchemaXSDAccordoServizio>();
  487.             List<String> namespaceSchemiImportati = new ArrayList<>();
  488.             readSchemi(listaSchemiImportati, namespaceSchemiImportati,schemiImportatiDalWsdl,schemiInclusiDalWsdl,wsdl,false,true);
  489.             //System.out.println("LETTI IMP: "+listaSchemiImportati.size()+" NS:"+namespaceSchemiImportati.size());
  490.            
  491.             List<SchemaXSDAccordoServizio> listaSchemiInclusi = new ArrayList<SchemaXSDAccordoServizio>();
  492.             List<String> namespaceSchemiInclusi = new ArrayList<>();
  493.             readSchemi(listaSchemiInclusi, namespaceSchemiInclusi,schemiImportatiDalWsdl,schemiInclusiDalWsdl,wsdl,true,false);
  494.             //System.out.println("LETTI INCL: "+listaSchemiImportati.size()+" NS:"+namespaceSchemiImportati.size());
  495.            
  496.             List<byte[]> schemiDaInglobareInWsdl = new ArrayList<byte[]>();
  497.            
  498.             String uniquePrefix = "_n"+IDUtilities.getUniqueSerialNumber("gestioneSchemiInBaseOutputMode_inputWsdl")+"_";
  499.            
  500.             // Schemi lasciati originali
  501.             if(this.outputMode.equals(StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI)){
  502.                 if(erogatore){
  503.                     this.schemiWsdlErogatore.addAll(listaSchemiImportati);
  504.                     this.schemiWsdlErogatore.addAll(listaSchemiInclusi);
  505.                 }else{
  506.                     this.schemiWsdlFruitore.addAll(listaSchemiImportati);
  507.                     this.schemiWsdlErogatore.addAll(listaSchemiInclusi);
  508.                 }
  509.             }
  510.            
  511.             // Schemi inglobati completamente nel wsdl
  512.             else if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SCHEMI_IN_WSDL) ){
  513.                
  514.                 for(int i=0;i<listaSchemiImportati.size();i++){
  515.                     SchemaXSD xsd = listaSchemiImportati.get(i);
  516.                     Element xsdElement = xsd.getXml();
  517.                     this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, true, null);
  518.                     this.xsdUtils.removeImportsAndIncludes(xsdElement);
  519.                     schemiDaInglobareInWsdl.add(xsd.toByteArray());
  520.                 }
  521.                
  522.                 for(int i=0;i<listaSchemiInclusi.size();i++){
  523.                     SchemaXSD xsd = listaSchemiInclusi.get(i);
  524.                     Element xsdElement = xsd.getXml();
  525.                     this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(xsdElement, wsdlElement, prefixForWSDL,uniquePrefix, false, namespaceSchemiInclusi.get(i));
  526.                     this.xsdUtils.removeImportsAndIncludes(xsdElement);
  527.                     schemiDaInglobareInWsdl.add(xsd.toByteArray());
  528.                 }
  529.             }
  530.            
  531.             // Schemi inglobati nel wsdl sono solo quelli che vengono inclusi dal wsdl stesso.
  532.             else if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_IN_WSDL) ||
  533.                     this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_NOME_AUTOGENERATO_IN_WSDL)  ){
  534.            
  535.                 for(int i=0;i<listaSchemiImportati.size();i++){
  536.                     SchemaXSDAccordoServizio xsd = listaSchemiImportati.get(i);
  537.                     Element xsdElement = xsd.getXml();
  538.                     this.wsdlUtilities.readPrefixForWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, false);
  539.                     if(erogatore){
  540.                         this.schemiWsdlErogatore.add(xsd);
  541.                     }else{
  542.                         this.schemiWsdlFruitore.add(xsd);
  543.                     }
  544.                 }
  545.                                            
  546.                 for(int i=0;i<listaSchemiInclusi.size();i++){
  547.                     SchemaXSDAccordoServizio xsd = listaSchemiInclusi.get(i);
  548.                     Element xsdElement = xsd.getXml();
  549.                    
  550.                     boolean schemaInclusoDalWsdl = false;
  551.                     for(int j=0; j<schemiInclusiDalWsdl.size();j++){
  552.                         Node n = schemiInclusiDalWsdl.get(j);
  553.                         String location = null;
  554.                         try{
  555.                             location = this.xsdUtils.getIncludeSchemaLocation(n);
  556.                         }catch(Exception e){
  557.                             // ignore
  558.                         }
  559.                         if(xsd.getSource()!=null && xsd.getSource().getAbsolutePath()!=null && xsd.getSource().getAbsolutePath().endsWith(location)){
  560.                            
  561.                             if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_NOME_AUTOGENERATO_IN_WSDL)){
  562.                                 File locationF = new File(location);
  563.                                 // check nome autogenerato
  564.                                 if(SplitWSDL.DEFINITORIO_FILENAME.equals(locationF.getName())){
  565.                                     schemaInclusoDalWsdl = true;
  566.                                     break;
  567.                                 }else if(locationF.getName().startsWith("InterfacciaDefinitoria_") && locationF.getName().endsWith(".xsd")){
  568.                                     schemaInclusoDalWsdl = true;
  569.                                     break;
  570.                                 }
  571.                             }
  572.                             else{
  573.                                 schemaInclusoDalWsdl = true;
  574.                                 break;
  575.                             }
  576.                         }
  577.                     }
  578.                    
  579.                     if(schemaInclusoDalWsdl){
  580.                         this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, false, namespaceSchemiInclusi.get(i));
  581.                         schemiDaInglobareInWsdl.add(xsd.toByteArray());
  582.                     }else{
  583.                         this.wsdlUtilities.readPrefixForWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, false);
  584.                         if(erogatore){
  585.                             this.schemiWsdlErogatore.add(xsd);
  586.                         }else{
  587.                             this.schemiWsdlFruitore.add(xsd);
  588.                         }
  589.                     }
  590.                 }
  591.             }
  592.            
  593.             // Schemi inglobati nel wsdl sono solo quelli che vengono importati dal wsdl stesso.
  594.             else if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_IMPORTATI_IN_WSDL) ){
  595.            
  596.                 for(int i=0;i<listaSchemiInclusi.size();i++){
  597.                     SchemaXSDAccordoServizio xsd = listaSchemiInclusi.get(i);
  598.                     Element xsdElement = xsd.getXml();
  599.                     this.wsdlUtilities.readPrefixForWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, false);
  600.                     if(erogatore){
  601.                         this.schemiWsdlErogatore.add(xsd);
  602.                     }else{
  603.                         this.schemiWsdlFruitore.add(xsd);
  604.                     }
  605.                 }
  606.                                
  607.                 for(int i=0;i<listaSchemiImportati.size();i++){
  608.                     SchemaXSDAccordoServizio xsd = listaSchemiImportati.get(i);
  609.                     Element xsdElement = xsd.getXml();
  610.                    
  611.                     boolean schemaImportatoDalWsdl = false;
  612.                     for(int j=0; j<schemiImportatiDalWsdl.size();j++){
  613.                         Node n = schemiImportatiDalWsdl.get(j);
  614.                         String location = null;
  615.                         try{
  616.                             location = this.xsdUtils.getImportSchemaLocation(n);
  617.                         }catch(Exception e){
  618.                             // ignore
  619.                         }
  620.                         if(xsd.getSource()!=null && xsd.getSource().getAbsolutePath()!=null && xsd.getSource().getAbsolutePath().endsWith(location)){
  621.                             schemaImportatoDalWsdl = true;
  622.                             break;
  623.                         }
  624.                     }
  625.                    
  626.                     if(schemaImportatoDalWsdl){
  627.                         this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, true, null);
  628.                         schemiDaInglobareInWsdl.add(xsd.toByteArray());
  629.                     }else{
  630.                         this.wsdlUtilities.readPrefixForWsdl(xsdElement, wsdlElement, prefixForWSDL, uniquePrefix, false);
  631.                         if(erogatore){
  632.                             this.schemiWsdlErogatore.add(xsd);
  633.                         }else{
  634.                             this.schemiWsdlFruitore.add(xsd);
  635.                         }
  636.                     }
  637.                 }
  638.             }
  639.            
  640.            
  641.            
  642.             //System.out.println("SCHEMI INGLOBATI: "+schemiDaInglobareInWsdl.size());
  643.             //System.out.println("SCHEMI EROGATORI: "+this.schemiErogatore.size());
  644.             //System.out.println("SCHEMI FRUITORI: "+this.schemiFruitore.size());
  645.            
  646.            
  647.            
  648.            
  649.             /* -------------  Elimino tutti gli schemi dal wsdl, e inoltre imposto i prefix corretti nel wsdl definition ----------------*/
  650.            
  651.             // Creo wsdl originale senza types
  652.             this.wsdlUtilities.removeTypes(documentWSDL);
  653.             DefinitionWrapper definitionTmp = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  654.             Types types = new TypesImpl();
  655.             definitionTmp.setTypes(types); // types è vuoto!
  656.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  657.             definitionTmp.writeTo(bout);
  658.             bout.flush();
  659.             bout.close();
  660.            
  661.             // Imposto nuovi prefix ottenuti dall'analisi degli schemi xsd
  662.             String wsdlTrasformato = bout.toString();
  663.             if(wsdlTrasformato.trim().startsWith("<?xml")){
  664.                 wsdlTrasformato = wsdlTrasformato.substring(wsdlTrasformato.indexOf(">")+1);
  665.             }
  666.             Iterator<String> keys = prefixForWSDL.keySet().iterator();
  667.             while(keys.hasNext()){
  668.                 String key = keys.next();
  669.                 //System.out.println("ADD ["+key+"] ["+prefixForWSDL.get(key)+"]");
  670.                 wsdlTrasformato = wsdlTrasformato.replaceFirst(">", " "+key+"=\""+prefixForWSDL.get(key)+"\">");
  671.             }
  672.            
  673.             // Riottengo definition object
  674.             documentWSDL = this.xmlUtils.newDocument(wsdlTrasformato.getBytes());
  675.             if(erogatore){
  676.                 this.wsdlErogatore = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  677.             }else{
  678.                 this.wsdlFruitore = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  679.             }
  680.            
  681.            
  682.            
  683.            
  684.            
  685.            
  686.             /* -------------  Riaggiungo import o include originali ----------------*/
  687.             if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_IN_WSDL) ||
  688.                     this.outputMode.equals(StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI) ||
  689.                     this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_NOME_AUTOGENERATO_IN_WSDL) ){
  690.                
  691.                 //System.out.println("ripristino import ("+schemiImportatiDalWsdl.size()+")");
  692.                
  693.                 // ripristino import
  694.                 for(int i=0; i<schemiImportatiDalWsdl.size();i++){
  695.                     Node n = schemiImportatiDalWsdl.get(i);
  696.                     String namespaceImport = null;
  697.                     try{
  698.                         namespaceImport = this.xsdUtils.getImportNamespace(n);
  699.                     }catch(Exception e){
  700.                         // ignore
  701.                     }
  702.                     String location = null;
  703.                     try{
  704.                         location = this.xsdUtils.getImportSchemaLocation(n);
  705.                     }catch(Exception e){
  706.                         // ignore
  707.                     }
  708.                     //System.out.println("Import ["+namespaceImport+"] ["+location+"]");
  709.                     String targetNamespacePadre =  null;
  710.                     Object o = n.getUserData("TargetNamespaceSchema");
  711.                     if(o!=null){
  712.                         targetNamespacePadre = (String)o;
  713.                     }
  714.                     if(targetNamespacePadre==null){
  715.                         targetNamespacePadre = namespaceImport;
  716.                     }
  717.                    
  718.                     String importSchema = "<xsd:schema targetNamespace=\""+targetNamespacePadre+"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
  719.                         "\t<xsd:import namespace=\""+namespaceImport+"\" schemaLocation=\""+location+"\"/>\n"+
  720.                         "</xsd:schema>\n";
  721.                     schemiDaInglobareInWsdl.add(importSchema.getBytes());
  722.                 }
  723.                                
  724.             }
  725.            
  726.             if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_IMPORTATI_IN_WSDL) ||
  727.                     this.outputMode.equals(StandardWSDLOutputMode.MANTIENI_IMPORT_INCLUDE_ORIGINALI) ){
  728.                
  729.                 //System.out.println("ripristino include ("+schemiInclusiDalWsdl.size()+")");
  730.                
  731.                 // ripristino include
  732.                 for(int i=0; i<schemiInclusiDalWsdl.size();i++){
  733.                     Node n = schemiInclusiDalWsdl.get(i);
  734.                     String location = null;
  735.                     try{
  736.                         location = this.xsdUtils.getIncludeSchemaLocation(n);
  737.                     }catch(Exception e){
  738.                         // ignore
  739.                     }
  740.                     //System.out.println("Include ["+location+"]");
  741.                     String targetNamespacePadre =  null;
  742.                     Object o = n.getUserData("TargetNamespaceSchema");
  743.                     if(o!=null){
  744.                         targetNamespacePadre = (String)o;
  745.                     }
  746.                                        
  747.                     String includeSchema = "<xsd:schema targetNamespace=\""+targetNamespacePadre+"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
  748.                         "\t<xsd:include schemaLocation=\""+location+"\"/>\n"+
  749.                         "</xsd:schema>\n";
  750.                     schemiDaInglobareInWsdl.add(includeSchema.getBytes());
  751.                 }
  752.                
  753.             }
  754.            
  755.             if(this.outputMode.equals(StandardWSDLOutputMode.INGLOBA_SOLO_SCHEMI_INCLUSI_NOME_AUTOGENERATO_IN_WSDL)){
  756.                
  757.                 //System.out.println("ripristino include con nome non autogenerato ("+schemiInclusiDalWsdl.size()+")");
  758.                
  759.                 // ripristino include
  760.                 for(int i=0; i<schemiInclusiDalWsdl.size();i++){
  761.                     Node n = schemiInclusiDalWsdl.get(i);
  762.                     String location = null;
  763.                     try{
  764.                         location = this.xsdUtils.getIncludeSchemaLocation(n);
  765.                     }catch(Exception e){
  766.                         // ignore
  767.                     }
  768.                     //System.out.println("Include ["+location+"]");
  769.                     if(location!=null) {
  770.                         File locationF = new File(location);
  771.                        
  772.                         // check nome autogenerato
  773.                         if(   !(   SplitWSDL.DEFINITORIO_FILENAME.equals(locationF.getName()) ||
  774.                                   (locationF.getName().startsWith("InterfacciaDefinitoria_") && locationF.getName().endsWith(".xsd"))
  775.                                )
  776.                             ){
  777.                            
  778.                             String targetNamespacePadre =  null;
  779.                             Object o = n.getUserData("TargetNamespaceSchema");
  780.                             if(o!=null){
  781.                                 targetNamespacePadre = (String)o;
  782.                             }
  783.                                                
  784.                             String includeSchema = "<xsd:schema targetNamespace=\""+targetNamespacePadre+"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
  785.                                 "\t<xsd:include schemaLocation=\""+location+"\"/>\n"+
  786.                                 "</xsd:schema>\n";
  787.                             schemiDaInglobareInWsdl.add(includeSchema.getBytes());
  788.                            
  789.                         }
  790.                     }
  791.                 }
  792.                
  793.             }

  794.            
  795.            
  796.            
  797.             /* -------- ritorno schemi da includere nel wsdl -------------- */
  798.             if(schemiDaInglobareInWsdl.size()>0){
  799.                 return schemiDaInglobareInWsdl;
  800.             }else{
  801.                 return null;
  802.             }
  803.            
  804.         }catch(Exception e){
  805.             throw new StandardWSDLException(e.getMessage(),e);
  806.         }
  807.     }
  808.    
  809.    
  810.     private void buildListaSchemiInclusi_inputByteArray(List<Node> inclusioni,List<SchemaXSDAccordoServizio> schemiInclusi,
  811.             List<String> namespacesInclusioni,List<SchemaXSDAccordoServizio> schemiCompleti,String targetNamespace)
  812.     throws StandardWSDLException,WSDLException,org.openspcoop2.utils.wsdl.WSDLException,IOException,ParserConfigurationException,SAXException,TransformerException,XMLException{
  813.         if(inclusioni!=null && inclusioni.size()>0){
  814.             for(int i=0; i<inclusioni.size();i++){
  815.                 Node nodo = inclusioni.get(i);
  816.                 buildListaSchemiInclusi_esaminaNodo_inputByteArray(inclusioni, schemiInclusi, namespacesInclusioni, schemiCompleti, nodo, true,targetNamespace);
  817.             }
  818.         }
  819.     }
  820.     private void buildListaSchemiInclusi_esaminaNodo_inputByteArray(List<Node> inclusioni,List<SchemaXSDAccordoServizio> schemiInclusi,
  821.             List<String> namespacesInclusioni,List<SchemaXSDAccordoServizio> schemiCompleti,Node nodo,boolean include,String targetNamespace)
  822.         throws StandardWSDLException,WSDLException,org.openspcoop2.utils.wsdl.WSDLException,IOException,ParserConfigurationException,SAXException,TransformerException,XMLException{
  823.        
  824.         String location = null;
  825.         if(include){
  826.             try{
  827.                 location = this.xsdUtils.getIncludeSchemaLocation(nodo);
  828.             }catch(Exception e){
  829.                 // ignore
  830.             }
  831.         }
  832.         else{
  833.             try{
  834.                 location = this.xsdUtils.getImportSchemaLocation(nodo);
  835.             }catch(Exception e){
  836.                 // ignore
  837.             }
  838.         }
  839.         if(location!=null) {
  840.             File locationF = new File(location);
  841.             String nome = locationF.getName();
  842.             if(locationF.getParentFile()==null){
  843.                 throw new StandardWSDLException("Trovato include di uno schema che non indica la directory "+CostantiRegistroServizi.ALLEGATI_DIR+" o "+CostantiRegistroServizi.SPECIFICA_SEMIFORMALE_DIR);
  844.             }
  845.             String padre = locationF.getParentFile().getName();
  846.        
  847.             // cerco lo schema incluso
  848.             for(int j=0; j<schemiCompleti.size();j++){
  849.                 SchemaXSDAccordoServizio tmp = schemiCompleti.get(j);
  850.                 if(tmp.getFilename().equals(nome) && tmp.getTipoSchema().getDirectory().equals(padre)){
  851.                     // trovato schema
  852.                    
  853.                     SchemaXSDAccordoServizio schemaXSD = schemiCompleti.get(j);
  854.                     if(include){
  855.                         schemiCompleti.remove(j);
  856.                        
  857.                         Object o = nodo.getUserData("TargetNamespaceSchema");
  858.                         if(o!=null){
  859.                             targetNamespace = (String)o;
  860.                         }
  861.                         namespacesInclusioni.add(targetNamespace);
  862.                         schemiInclusi.add(schemaXSD);              
  863.                     }
  864.                    
  865.                     buildListaSchemiInclusi_inputByteArray(this.xsdUtils.readIncludes(targetNamespace,schemaXSD.getXml()),
  866.                             schemiInclusi,namespacesInclusioni,schemiCompleti,targetNamespace);
  867.                    
  868.                     break;
  869.    
  870.                 }
  871.             }
  872.         }
  873.        
  874.     }
  875.     private List<byte[]> gestioneSchemiInBaseOutputMode_inputByteArray(boolean erogatore,List<SchemaXSDAccordoServizio> schemiXSD,
  876.             HashMap<String,String> prefixForWSDL, String uniquePrefix) throws StandardWSDLException{
  877.        
  878.         try{
  879.            
  880.             @SuppressWarnings("unchecked")
  881.             List<SchemaXSDAccordoServizio> schemi = (List<SchemaXSDAccordoServizio>) ((ArrayList<SchemaXSDAccordoServizio>) schemiXSD).clone();
  882.            
  883.             Document documentWSDL = null;
  884.             if(erogatore){
  885.                 documentWSDL = this.xmlUtils.newDocument(this.wsdlErogatore.toByteArray());
  886.             }
  887.             else{
  888.                 documentWSDL = this.xmlUtils.newDocument(this.wsdlFruitore.toByteArray());
  889.             }
  890.             String targetNamespaceWSDL = this.wsdlUtilities.getTargetNamespace(documentWSDL);
  891.            
  892.             List<SchemaXSDAccordoServizio> schemiInclusi = new ArrayList<SchemaXSDAccordoServizio>();
  893.             List<String> namespacesInclusioni = new ArrayList<>();
  894.             List<Node> inclusioni = this.wsdlUtilities.readIncludesSchemaIntoTypes(documentWSDL);
  895.             //System.out.println("TROVATE INCLUSIONI NEL WSDL: "+inclusioni.size());
  896.             buildListaSchemiInclusi_inputByteArray(inclusioni, schemiInclusi, namespacesInclusioni ,schemi,targetNamespaceWSDL);
  897.             List<Node> imports = this.wsdlUtilities.readImportsSchemaIntoTypes(documentWSDL);
  898.             //System.out.println("TROVATE IMPORT NEL WSDL: "+imports.size());
  899.             for(int i=0; i<imports.size();i++){
  900.                 Node nodo = imports.get(i);
  901.                 buildListaSchemiInclusi_esaminaNodo_inputByteArray(inclusioni, schemiInclusi, namespacesInclusioni, schemi, nodo, false,targetNamespaceWSDL);
  902.             }
  903.             // In schemi sono rimasti solo gli imports
  904.             //System.out.println("INCLUDE["+schemiInclusi.size()+"] IMPORTS["+schemi.size()+"]");
  905.            
  906.             Element wsdlElement = documentWSDL.getDocumentElement();
  907.             List<byte[]> schemiInglobareWsdl = new ArrayList<byte[]>();
  908.            
  909.             // includes
  910.             for(int i=0; i<schemiInclusi.size();i++){
  911.                 try{
  912.                     //System.out.println("GESTIONE INCLUDE: "+schemiInclusi.get(i).getFilename());
  913.                     Element schemaXML = (Element) schemiInclusi.get(i).getXml().cloneNode(true); // per non modificare l'originale
  914.                     this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(schemaXML, wsdlElement, prefixForWSDL, uniquePrefix, false, namespacesInclusioni.get(i));
  915.                     this.xsdUtils.removeImportsAndIncludes(schemaXML);
  916.                     schemiInglobareWsdl.add(this.xmlUtils.toByteArray(schemaXML));
  917.                 }catch(Exception e){
  918.                     throw new StandardWSDLException(e.getMessage(),e);
  919.                 }
  920.             }
  921.            
  922.             // imports
  923.             for(int i=0; i<schemi.size();i++){
  924.                 try{
  925.                     //System.out.println("GESTIONE IMPORT: "+schemi.get(i).getFilename());
  926.                     Element schemaXML = (Element) schemi.get(i).getXml().cloneNode(true); // per non modificare l'originale
  927.                     this.wsdlUtilities.normalizzazioneSchemaPerInserimentoInWsdl(schemaXML, wsdlElement, prefixForWSDL, uniquePrefix, true, null);
  928.                     this.xsdUtils.removeImportsAndIncludes(schemaXML);
  929.                     schemiInglobareWsdl.add(this.xmlUtils.toByteArray(schemaXML));
  930.                 }catch(Exception e){
  931.                     throw new StandardWSDLException(e.getMessage(),e);
  932.                 }
  933.             }
  934.            
  935.             // Creo wsdl originale senza types
  936.             this.wsdlUtilities.removeTypes(documentWSDL);
  937.             DefinitionWrapper definitionTmp = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  938.             Types types = new TypesImpl();
  939.             definitionTmp.setTypes(types); // types è vuoto!
  940.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  941.             definitionTmp.writeTo(bout);
  942.             bout.flush();
  943.             bout.close();
  944.            
  945.             // Imposto nuovi prefix ottenuti dall'analisi degli schemi xsd
  946.             String wsdlTrasformato = bout.toString();
  947.             if(wsdlTrasformato.trim().startsWith("<?xml")){
  948.                 wsdlTrasformato = wsdlTrasformato.substring(wsdlTrasformato.indexOf(">")+1);
  949.             }
  950.             Iterator<String> keys = prefixForWSDL.keySet().iterator();
  951.             while(keys.hasNext()){
  952.                 String key = keys.next();
  953.                 //System.out.println("ADD ["+key+"] ["+prefixForWSDL.get(key)+"]");
  954.                 wsdlTrasformato = wsdlTrasformato.replaceFirst(">", " "+key+"=\""+prefixForWSDL.get(key)+"\">");
  955.             }
  956.            
  957.             // Riottengo definition object
  958.             documentWSDL = this.xmlUtils.newDocument(wsdlTrasformato.getBytes());
  959.             if(erogatore)
  960.                 this.wsdlErogatore = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  961.             else
  962.                 this.wsdlFruitore = new DefinitionWrapper(documentWSDL,this.xmlUtils,false,false);
  963.            
  964.             return schemiInglobareWsdl;
  965.            
  966.         }catch(Exception e){
  967.             throw new StandardWSDLException(e.getMessage(),e);
  968.         }
  969.        
  970.     }
  971.    
  972.     /**
  973.      * Recupera l'array dei documenti in xsd:include
  974.      * @param wsdl
  975.      * @return array dei documenti in xsd:include
  976.      * @throws IOException
  977.      */
  978.     private void readSchemi(List<SchemaXSDAccordoServizio> schemi, List<String> namespaceSchemi,
  979.             List<Node> schemiImportatiWSDL,List<Node> schemiInclusiWSDL,
  980.             DefinitionWrapper wsdl,boolean readIncludes,boolean readImports) throws StandardWSDLException{
  981.         try{
  982.             Types types = wsdl.getTypes();
  983.             if(types!=null){
  984.                 List<?> xsdTypes = types.getExtensibilityElements();
  985.                 for (int i = 0; i< xsdTypes.size(); i++){
  986.                     Schema schema = (Schema) xsdTypes.get(i);
  987.                     String targetNamespaceSchema = this.wsdlUtilities.getTargetNamespace(schema);
  988.                     readSchemi(schemi, namespaceSchemi, schemiImportatiWSDL, schemiInclusiWSDL,
  989.                             schema.getElement(), readIncludes, readImports, targetNamespaceSchema,0);
  990.                 }
  991.             }          
  992.         }catch(Exception e){
  993.             throw new StandardWSDLException(e.getMessage(),e);
  994.         }
  995.     }
  996.     private void readSchemi(List<SchemaXSDAccordoServizio> schemi,List<String> namespaceSchemi,
  997.             List<Node> schemiImportatiWSDL,List<Node> schemiInclusiWSDL,
  998.             Element schema,boolean readIncludes,boolean readImports,
  999.             String targetNamespacePadre, int profondita) throws StandardWSDLException{
  1000.    
  1001.         try{
  1002.             boolean wsdl = false;
  1003.             if(profondita==0){
  1004.                 wsdl = true;
  1005.             }
  1006.            
  1007.             // Leggo gli includes
  1008.             List<Node> includes = this.xsdUtils.readIncludes(schema);
  1009.             for (int j = 0; j< includes.size(); j++){
  1010.                 Node n = includes.get(j);
  1011.                 String location = null;
  1012.                 try{
  1013.                     location = this.xsdUtils.getIncludeSchemaLocation(n);
  1014.                 }catch(Exception e){
  1015.                     // ignore
  1016.                 }
  1017.                 if(location!=null){
  1018.                     File fLocation = null;
  1019.                     if(this.pathLogico!=null){
  1020.                         fLocation = new File(this.pathLogico,location);
  1021.                     }else{
  1022.                         fLocation = new File(location);
  1023.                     }
  1024.                     byte [] schemaBytes = FileSystemUtilities.readBytesFromFile(fLocation);
  1025.                     SchemaXSDAccordoServizio schemaXSD = SchemaXSDAccordoServizio.creaSchema(schemaBytes, fLocation);
  1026.                     //System.out.println("INCLUDE LOCATION ["+location+"] NS["+targetNamespacePadre+"]");
  1027.                     readSchemi(schemi, namespaceSchemi, schemiImportatiWSDL, schemiInclusiWSDL, schemaXSD.getXml(), readIncludes, readImports, targetNamespacePadre, ++profondita);
  1028.                     if(readIncludes){
  1029.                         schemi.add(schemaXSD);
  1030.                         namespaceSchemi.add(targetNamespacePadre);
  1031.                         if(wsdl){
  1032.                             //System.out.println("SCHEMA INCLUSO DAL WSDL ("+targetNamespacePadre+"): "+location);
  1033.                             n.setUserData("TargetNamespaceSchema", targetNamespacePadre, null);
  1034.                             schemiInclusiWSDL.add(n);
  1035.                         }
  1036.                     }
  1037.                 }
  1038.             }
  1039.                    
  1040.            
  1041.             // Leggo gli imports
  1042.             List<Node> imports = this.xsdUtils.readImports(schema);
  1043.             for (int j = 0; j< imports.size(); j++){
  1044.                 Node n = imports.get(j);
  1045.                 String location = null;
  1046.                 try{
  1047.                     location = this.xsdUtils.getImportSchemaLocation(n);
  1048.                 }catch(Exception e){
  1049.                     // ignore
  1050.                 }
  1051.                 if(location!=null){
  1052.                     File fLocation = null;
  1053.                     if(this.pathLogico!=null){
  1054.                         fLocation = new File(this.pathLogico,location);
  1055.                     }else{
  1056.                         fLocation = new File(location);
  1057.                     }
  1058.                     byte [] schemaBytes = FileSystemUtilities.readBytesFromFile(fLocation);
  1059.                     SchemaXSDAccordoServizio schemaXSD = SchemaXSDAccordoServizio.creaSchema(schemaBytes, fLocation);
  1060.                     String targetNamespaceXSD = this.xsdUtils.getTargetNamespace(schemaXSD.getXml());
  1061.                     //System.out.println("IMPORT LOCATION ["+location+"] NS["+targetNamespace+"]");
  1062.                     readSchemi(schemi, namespaceSchemi, schemiImportatiWSDL, schemiInclusiWSDL, schemaXSD.getXml(), readIncludes, readImports, targetNamespaceXSD, ++profondita);
  1063.                     if(readImports){
  1064.                         schemi.add(schemaXSD);
  1065.                         namespaceSchemi.add(targetNamespaceXSD);
  1066.                         if(wsdl){
  1067.                             //System.out.println("SCHEMA IMPORTATO DAL WSDL ("+targetNamespace+"): "+location);
  1068.                             n.setUserData("TargetNamespaceSchema", targetNamespaceXSD, null);
  1069.                             schemiImportatiWSDL.add(n);
  1070.                         }
  1071.                     }
  1072.                 }
  1073.             }  
  1074.            
  1075.         }catch(Exception e){
  1076.             throw new StandardWSDLException(e.getMessage(),e);
  1077.         }
  1078.        
  1079.     }
  1080.    
  1081.    
  1082.    
  1083.     /**
  1084.      * Svuota il wsdl:types e lo riempie con gli xsd:schema nel vettore degli schemi
  1085.      * @param schemi
  1086.      * @param wsdl
  1087.      * @return DefinitionWrapper
  1088.      * @throws ParserConfigurationException
  1089.      * @throws IOException
  1090.      * @throws SAXException
  1091.      * @throws WSDLException
  1092.      * @throws XMLException
  1093.      */
  1094.     private DefinitionWrapper addSchemiWsdlTypes(DefinitionWrapper wsdl, List<byte[]> schemi) throws ParserConfigurationException, SAXException, IOException, WSDLException, XMLException{
  1095.         // Se non mi sono stati passati gli schemi, ritorno il wsdl originale.
  1096.         DefinitionWrapper result = new DefinitionWrapper(wsdl,this.xmlUtils);
  1097.         if(schemi == null || schemi.size() == 0) return wsdl;
  1098.        
  1099.         Types types = result.getTypes();
  1100.         if(types != null){
  1101.             List<?> xsdTypes = types.getExtensibilityElements();
  1102.             while (xsdTypes.size()>0){
  1103.                 types.removeExtensibilityElement((Schema) xsdTypes.get(0));
  1104.                 xsdTypes = types.getExtensibilityElements();
  1105.             }
  1106.         } else {
  1107.             types = result.createTypes();
  1108.             result.setTypes(types);
  1109.         }
  1110.        
  1111.         for(int i=0; i<schemi.size(); i++){
  1112.             if(schemi.get(i) == null) continue;
  1113.             Document schemaDoc =  this.xmlUtils.newDocument(schemi.get(i));
  1114.             Schema schema = new SchemaImpl();
  1115.             schema.setElementType(new QName("http://www.w3.org/2001/XMLSchema","schema"));
  1116.             schema.setElement(schemaDoc.getDocumentElement());
  1117.             types.addExtensibilityElement(schema);
  1118.         }
  1119.        
  1120.         return result;
  1121.     }
  1122.    
  1123.     private void addImportsAndTypesToWsdl(DefinitionWrapper wsdl,List<Node> importsPresentiWsdl,
  1124.             List<Node> includesTypesPresentiWsdl,
  1125.             List<Node> importsTypesPresentiWsdl) throws WSDLException,IOException,SAXException,ParserConfigurationException, XMLException{
  1126.        
  1127.         if(wsdl==null) {
  1128.             throw new XMLException("Param wsdl is null");
  1129.         }
  1130.         if(importsPresentiWsdl==null) {
  1131.             throw new XMLException("Param importsPresentiWsdl is null");
  1132.         }
  1133.         if(includesTypesPresentiWsdl==null) {
  1134.             throw new XMLException("Param includesTypesPresentiWsdl is null");
  1135.         }
  1136.         if(importsTypesPresentiWsdl==null) {
  1137.             throw new XMLException("Param importsTypesPresentiWsdl is null");
  1138.         }
  1139.        
  1140.         // riaggiungo wsdl import
  1141.         //System.out.println("RIAGGIUNGO WSDL IMPORT ("+importsPresentiWsdl.size()+")");
  1142.         for(int i=0; i<importsPresentiWsdl.size(); i++){
  1143.             Node wsdlImport = importsPresentiWsdl.get(i);
  1144.             String namespaceImport = null;
  1145.             try{
  1146.                 namespaceImport = this.wsdlUtilities.getImportNamespace(wsdlImport);
  1147.             }catch(Exception e){
  1148.                 // ignore
  1149.             }
  1150.             String location = null;
  1151.             try{
  1152.                 location = this.wsdlUtilities.getImportLocation(wsdlImport);
  1153.             }catch(Exception e){
  1154.                 // ignore
  1155.             }
  1156.             Import importWsdl = new ImportImpl();
  1157.             importWsdl.setLocationURI(location);
  1158.             importWsdl.setNamespaceURI(namespaceImport);
  1159.             //System.out.println("ADD ["+namespaceImport+"] ["+location+"]");
  1160.             wsdl.addImport(importWsdl);
  1161.         }
  1162.        
  1163.        
  1164.         List<byte[]> listaWsdlTypes = new ArrayList<byte[]>();
  1165.        
  1166.         // riaggiungo types:includes
  1167.         //System.out.println("RIAGGIUNGO WSDL TYPES INCLUDES ("+includesTypesPresentiWsdl.size()+")");
  1168.         for(int i=0; i<includesTypesPresentiWsdl.size(); i++){
  1169.             Node xsdIncludes = includesTypesPresentiWsdl.get(i);
  1170.             String location = null;
  1171.             try{
  1172.                 location = this.xsdUtils.getIncludeSchemaLocation(xsdIncludes);
  1173.             }catch(Exception e){
  1174.                 // ignore
  1175.             }
  1176.             String targetNamespacePadre = (String) xsdIncludes.getUserData("TargetNamespaceSchema");
  1177.             String includeSchema = "<xsd:schema targetNamespace=\""+targetNamespacePadre+"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
  1178.                 "\t<xsd:include schemaLocation=\""+location+"\"/>\n"+
  1179.                 "</xsd:schema>\n";
  1180.             //System.out.println("ADD P["+targetNamespacePadre+"] ["+location+"]");
  1181.             listaWsdlTypes.add(includeSchema.getBytes());
  1182.         }
  1183.        
  1184.         // riaggiungo types:imports
  1185.         //System.out.println("RIAGGIUNGO WSDL TYPES IMPORTS ("+importsTypesPresentiWsdl.size()+")");
  1186.         for(int i=0; i<importsTypesPresentiWsdl.size(); i++){
  1187.             Node xsdImport = importsTypesPresentiWsdl.get(i);
  1188.             String namespaceImport = null;
  1189.             try{
  1190.                 namespaceImport = this.xsdUtils.getImportNamespace(xsdImport);
  1191.             }catch(Exception e){
  1192.                 // ignore
  1193.             }
  1194.             //System.out.println("TargetNamespace schema xsd che contiene l'import: "+targetNamespaceXSD);
  1195.             String location = null;
  1196.             try{
  1197.                 location = this.xsdUtils.getImportSchemaLocation(xsdImport);
  1198.             }catch(Exception e){
  1199.                 // ignore
  1200.             }
  1201.             String targetNamespacePadre = null;
  1202.             Object o = xsdImport.getUserData("TargetNamespaceSchema");
  1203.             if(o!=null){
  1204.                 targetNamespacePadre = (String)o;
  1205.             }
  1206.             if(targetNamespacePadre==null){
  1207.                 targetNamespacePadre = namespaceImport;
  1208.             }
  1209.             String importSchema = "<xsd:schema targetNamespace=\""+targetNamespacePadre+"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"+
  1210.                 "\t<xsd:import namespace=\""+namespaceImport+"\" schemaLocation=\""+location+"\"/>\n"+
  1211.                 "</xsd:schema>\n";
  1212.             //System.out.println("ADD P["+targetNamespacePadre+"] ["+namespaceImport+"] ["+location+"]");
  1213.             listaWsdlTypes.add(importSchema.getBytes());
  1214.         }
  1215.        
  1216.         this.addSchemiWsdlTypes(wsdl, listaWsdlTypes);
  1217.     }
  1218.    
  1219.    
  1220.    
  1221.    
  1222.    
  1223.    
  1224.     /* ------------------- IMPORT WSDL LOGICO ----------------------------- */
  1225.    
  1226.     /**
  1227.      * Risolve l'import del wsdlLogico all'interno dell'implementativo
  1228.      * @param logico
  1229.      * @param risultato
  1230.      * @throws StandardWSDLException
  1231.      * @throws WSDLException
  1232.      */
  1233.     private DefinitionWrapper importLogico(DefinitionWrapper implementativo, DefinitionWrapper logico, boolean setupFromBytes) throws StandardWSDLException, WSDLException{
  1234.         if(implementativo == null){
  1235.             throw new StandardWSDLException("Implementativo non puo' essere null.");
  1236.         }
  1237.         DefinitionWrapper risultato = null;

  1238.         // Cerco l'import del wsdlLogico.
  1239.         Map<?,?> importsMap = implementativo.getImports();
  1240.        
  1241.         // Se mi e' stato passato il wsdl logico, accetto che non ci sia l'import, altrimenti lancio un'eccezione.
  1242.         if(importsMap.size() == 0 && logico == null){
  1243.             throw new StandardWSDLException("Implementativi che non importano il Logico non sono supportati da questo tool.");
  1244.         }
  1245.         if(importsMap.size() > 1){
  1246.             throw new StandardWSDLException("Implementativi che importano altri wsdl oltre al Logico non sono supportati da questo tool.");
  1247.         }
  1248.         Import importLogico = null;
  1249.         if(importsMap.size() == 1){
  1250.             Iterator<?> it = importsMap.values().iterator();
  1251.             List<?> imports = (List<?>) it.next();
  1252.             if(imports.size() != 1){
  1253.                 throw new StandardWSDLException("Implementativi che importano altri wsdl oltre al Logico non sono supportati da questo tool.");
  1254.             }  
  1255.             importLogico = (Import) imports.get(0);
  1256.         }
  1257.        
  1258.        
  1259.         if(setupFromBytes) { // vecchio logico!=null
  1260.             risultato = new DefinitionWrapper(logico,this.xmlUtils);
  1261.         } else {
  1262.             File importFile = null;
  1263.             if(importLogico==null) {
  1264.                 throw new StandardWSDLException("WSDL logico non fornito");
  1265.             }
  1266.             if(this.pathImplementativo!=null){
  1267.                 importFile = new File(new File(this.pathImplementativo), importLogico.getLocationURI());
  1268.             }else{
  1269.                 importFile = new File(importLogico.getLocationURI());
  1270.             }
  1271.             this.pathLogico = importFile.getParent();
  1272.             if (importFile.getName().compareTo(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL) == 0 || importFile.getName().compareTo(CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL) == 0){
  1273.                 // Carico il logico nel risultato
  1274.                 risultato = new DefinitionWrapper(importFile.getAbsolutePath(),this.xmlUtils);
  1275.             } else {
  1276.                 throw new StandardWSDLException("Implementativi che importano un wsdl Logico con nome diverso da " + CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL + " o " +CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL + " non sono supportati da questo tool.");
  1277.             }
  1278.         }
  1279.        
  1280.         // Controllo che i target siano gli stessi
  1281.         if(implementativo.getTargetNamespace().compareTo(risultato.getTargetNamespace()) != 0)
  1282.             throw new StandardWSDLException("Implementativo e Logico con targetNamespace diversi non sono supportati da questo tool.");
  1283.        
  1284.        
  1285.         // Prendo la definizione dei PortType e dei Services e li inserisco nel risultato.
  1286.         // Binding
  1287.         Map<?,?> bindings = implementativo.getBindings();
  1288.         Iterator<?> it = bindings.values().iterator();
  1289.         while(it.hasNext()){
  1290.             Binding bd = (Binding) it.next();
  1291.             risultato.addBinding(bd);
  1292.         }

  1293.         // Services
  1294.         Map<?,?> services = implementativo.getServices();
  1295.         it = services.values().iterator();
  1296.         while(it.hasNext()){
  1297.             Service s = (Service) it.next();
  1298.             risultato.addService(s);
  1299.         }
  1300.        
  1301.         return risultato;
  1302.     }
  1303.    
  1304.    
  1305.    
  1306.    
  1307.    
  1308.    
  1309.    
  1310.    
  1311.     /* ------------------- UTILITIES GENERALI ----------------------------- */
  1312.        
  1313.     private String getParentFile(String file){
  1314.         File f = new File(file);
  1315.         if(f.getParentFile()!=null){
  1316.             return f.getParentFile().getAbsolutePath();
  1317.         }else{
  1318.             return null;
  1319.         }
  1320.     }
  1321.    
  1322.     private Document cleanupWsdlImportsAndTypes(Document doc) {
  1323.         Element description = doc.getDocumentElement();
  1324.         NodeList imports = description.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "import");
  1325.         for(int i=0; i<imports.getLength(); i++){
  1326.             description.removeChild(imports.item(i));
  1327.         }
  1328.         NodeList types = description.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types");
  1329.         for(int i=0; i<types.getLength(); i++){
  1330.             description.removeChild(types.item(i));
  1331.         }
  1332.         return doc;
  1333.     }
  1334.    
  1335.     /**
  1336.      * Esegue il merge dei due wsdl.
  1337.      * @param a
  1338.      * @param b
  1339.      * @return DefinitionWrapper
  1340.      * @throws StandardWSDLException
  1341.      * @throws WSDLException
  1342.      */
  1343.     private DefinitionWrapper join(DefinitionWrapper a, DefinitionWrapper b) throws StandardWSDLException, WSDLException{
  1344.         if(a == null) return b;
  1345.         if(b == null) return a;
  1346.        
  1347.         DefinitionWrapper result = new DefinitionWrapper(a,this.xmlUtils);
  1348.        
  1349.        
  1350.         // Controllo che i due abbiano il solito target
  1351.        
  1352.         if(a.getTargetNamespace().compareTo(b.getTargetNamespace()) != 0){
  1353.             throw new StandardWSDLException("Erogatore e Fruitore con targetNamespace diversi non sono supportati da questo tool.");
  1354.         }
  1355.        
  1356.         // Namespace
  1357.         // Cerco le dichiarazioni di namespace di B che non sono in A e li aggiungo in risultato. (quelli di A ci sono gia')
  1358.        
  1359.         Map<?,?> namespacesBMap = b.getNamespaces();
  1360.         Map<?,?> namespacesAMap = a.getNamespaces();
  1361.         java.util.Iterator<?> prefixesIt = namespacesBMap.keySet().iterator();
  1362.         while(prefixesIt.hasNext()){
  1363.             String prefix = (String) prefixesIt.next();
  1364.             // Controllo se questo prefisso e' gia usato.
  1365.             String namespace = (String) namespacesAMap.get(prefix);
  1366.             if(namespace == null){
  1367.                 // Non c'e', lo aggiungo
  1368.                 result.addNamespace(prefix, (String) namespacesBMap.get(prefix));
  1369.             } else {
  1370.                 // Prefisso gia in uso. Se il namespace e' lo stesso, tutto ok, altrimenti lancio un'eccezione.
  1371.                 if(namespace.compareTo((String) namespacesBMap.get(prefix)) != 0)
  1372.                     throw new StandardWSDLException("Erogatore e Fruitore usano lo stesso prefisso per due namespace distinti. Impossibile fare il merge.");
  1373.             }
  1374.            
  1375.         }
  1376.        
  1377.         // Imports
  1378.         // Cerco gli import di B che non sono in A e li aggiungo in risultato (Quelli di A ci sono gia').
  1379.        
  1380.         Map<?,?> importBMap = b.getImports();
  1381.         Map<?,?> importAMap = a.getImports();
  1382.         java.util.Iterator<?> itb = importBMap.keySet().iterator();
  1383.         while(itb.hasNext()){
  1384.             String namespace = (String) itb.next();
  1385.             List<?> listb = (List<?>) importBMap.get(namespace);
  1386.             List<?> lista = (List<?>) importAMap.get(namespace);
  1387.            
  1388.             for(int i =0; i<listb.size(); i++){
  1389.                 Import importB = (Import) listb.get(i);
  1390.                 boolean found = false;
  1391.                 for(int j=0; j<lista.size(); j++){
  1392.                     Import importA = (Import) lista.get(j);
  1393.                     if(importB.getLocationURI().compareTo(importA.getLocationURI()) == 0 && importB.getNamespaceURI().compareTo(importA.getNamespaceURI()) == 0){
  1394.                         //System.out.println("Trovato: " + importA.getLocationURI());
  1395.                         found = true;
  1396.                     }
  1397.                 }
  1398.                 if(!found) {
  1399.                     result.addImport(importB);
  1400.                 }
  1401.             }
  1402.         }
  1403.        
  1404.         // Messaggi
  1405.         // Cerco la definizione dei messaggi di B che non sono in A e li aggiungo in risultato (Quelli di A ci sono gia').
  1406.        
  1407.         Map<?,?> messages = b.getMessages();
  1408.         Iterator<?> it = messages.values().iterator();
  1409.         while(it.hasNext()){
  1410.             Message msg = (Message) it.next();
  1411.             if(a.getMessage(msg.getQName()) == null){
  1412.                 //System.out.println("Aggiunto " + msg.getQName());
  1413.                 result.addMessage(msg);
  1414.             }
  1415.         }
  1416.        
  1417.         // PortTypes
  1418.         // Cerco la definizione dei PortTypes di B che non sono in A e li aggiungo in risultato (Quelli di A ci sono gia').
  1419.        
  1420.         Map<?,?> ports = b.getPortTypes();
  1421.         it = ports.values().iterator();
  1422.         while(it.hasNext()){
  1423.             PortType port = (PortType) it.next();
  1424.             if(a.getPortType(port.getQName()) == null){
  1425.                 //System.out.println("Aggiunto " + port.getQName());
  1426.                 result.addPortType(port);
  1427.             }
  1428.         }
  1429.        
  1430.         // Bindings
  1431.         // Cerco la definizione dei PortTypes di B che non sono in A e li aggiungo in risultato (Quelli di A ci sono gia').
  1432.        
  1433.         Map<?,?> bindings = b.getBindings();
  1434.         it = bindings.values().iterator();
  1435.         while(it.hasNext()){
  1436.             Binding binding = (Binding) it.next();
  1437.             if(a.getBinding(binding.getQName()) == null){
  1438.                 //System.out.println("Aggiunto " + binding.getQName());
  1439.                 result.addBinding(binding);
  1440.             }
  1441.         }
  1442.        
  1443.         // Services
  1444.         // Cerco la definizione dei Services di B che non sono in A e li aggiungo in risultato (Quelli di A ci sono gia').
  1445.        
  1446.         Map<?,?> services = b.getServices();
  1447.         it = services.values().iterator();
  1448.         while(it.hasNext()){
  1449.             Service service = (Service) it.next();
  1450.             if(a.getService(service.getQName()) == null){
  1451.                 //System.out.println("Aggiunto " + service.getQName());
  1452.                 result.addService(service);
  1453.             }
  1454.         }
  1455.         return result;
  1456.     }
  1457.        
  1458.     /**
  1459.      * Fonde i due array evitando duplici entry
  1460.      * @param a
  1461.      * @param b
  1462.      * @return Lista
  1463.      */
  1464.     private List<byte[]> join(List<byte[]> a, List<byte[]> b){
  1465.         List<byte[]> c = new ArrayList<byte[]>();
  1466.        
  1467.         // Inserisco gli elementi di a
  1468.         for(int i = 0; i<a.size(); i++){
  1469.             c.add(a.get(i));
  1470.         }
  1471.        
  1472.         // Inserisco gli elementi di b
  1473.         for(int i = 0; i<b.size(); i++){
  1474.             // Controllo che non ci sia gia'
  1475.             String bi = new String(b.get(i));
  1476.             boolean found = false;
  1477.             for(int j = 0; j<a.size(); j++){
  1478.                 String aj = new String(a.get(j));
  1479.                 if(bi.compareTo(aj) == 0) found = true;
  1480.             }
  1481.             if(!found){
  1482.                 c.add(b.get(i));
  1483.             }
  1484.         }
  1485.         return c;
  1486.     }
  1487.    
  1488.    
  1489.    
  1490. }