SplitWSDL.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.File;
  22. import java.io.IOException;
  23. import java.util.ArrayList;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Set;

  28. import javax.wsdl.Binding;
  29. import javax.wsdl.BindingOperation;
  30. import javax.wsdl.Import;
  31. import javax.wsdl.Message;
  32. import javax.wsdl.Operation;
  33. import javax.wsdl.Port;
  34. import javax.wsdl.PortType;
  35. import javax.wsdl.Service;
  36. import javax.wsdl.Types;
  37. import javax.wsdl.WSDLElement;
  38. import javax.wsdl.WSDLException;
  39. import javax.wsdl.extensions.ExtensibilityElement;
  40. import javax.wsdl.extensions.schema.Schema;
  41. import javax.xml.namespace.QName;
  42. import javax.xml.parsers.ParserConfigurationException;
  43. import javax.xml.transform.TransformerConfigurationException;
  44. import javax.xml.transform.TransformerException;
  45. import javax.xml.transform.TransformerFactoryConfigurationError;

  46. import org.openspcoop2.core.registry.constants.CostantiRegistroServizi;
  47. import org.openspcoop2.message.xml.MessageXMLUtils;
  48. import org.openspcoop2.utils.wsdl.DefinitionWrapper;
  49. import org.openspcoop2.utils.wsdl.WSDLUtilities;
  50. import org.openspcoop2.utils.xml.XMLException;
  51. import org.w3c.dom.Document;
  52. import org.w3c.dom.Element;
  53. import org.w3c.dom.NodeList;
  54. import org.xml.sax.SAXException;

  55. import com.ibm.wsdl.extensions.schema.SchemaImpl;

  56. /**
  57.  * Classe per la creazione dei WSDL suddivisi in schemi, parte comune e parte specifica a partire da WSDL standard.
  58.  *
  59.  * @author Lorenzo Nardi (nardi@link.it)
  60.  * @author $Author$
  61.  * @version $Rev$, $Date$
  62.  *
  63.  */
  64. public class SplitWSDL {
  65.    
  66.     /** Costanti */
  67.     public static final String FOLDER_IMPLEMENTATIVI = CostantiRegistroServizi.SPECIFICA_PORTI_ACCESSO_DIR;
  68.     public static final String IMPLEMENTATIVO_EROGATORE_FILENAME = CostantiRegistroServizi.SPECIFICA_PORTI_ACCESSO_EROGATORE_WSDL;
  69.     public static final String IMPLEMENTATIVO_FRUITORE_FILENAME = CostantiRegistroServizi.SPECIFICA_PORTI_ACCESSO_FRUITORE_WSDL;
  70.    
  71.     public static final String FOLDER_INTERFACCE = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_DIR;
  72.     public static final String LOGICO_EROGATORE_FILENAME = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_EROGATORE_WSDL;
  73.     public static final String LOGICO_FRUITORE_FILENAME = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_LOGICA_FRUITORE_WSDL;
  74.     public static final String CONCETTUALE_FILENAME = CostantiRegistroServizi.SPECIFICA_INTERFACCIA_CONCETTUALE_WSDL;
  75.     public static final String DEFINITORIO_FILENAME = CostantiRegistroServizi.ALLEGATO_DEFINITORIO_XSD;
  76.    
  77.    
  78.     /* ------- INPUT --------- */
  79.     /** WSDL erogatore. */
  80.     private DefinitionWrapper wsdlErogatore;
  81.     private String wsdlErogatorePath;
  82.     /** WSDL Fruitore */
  83.     private DefinitionWrapper wsdlFruitore;
  84.     private String wsdlFruitorePath;
  85.     /** Array dei nomi PortType e Operations per la divisione del wsdl */
  86.     private String[] porttypesErogatore;
  87.     private String[] operationPorttypesErogatore;
  88.     private String[] porttypesFruitore;
  89.     private String[] operationPorttypesFruitore;
  90.    
  91.    
  92.     /* ------- OUTPUT --------- */
  93.     /** WSDL implementativo erogatore */
  94.     private DefinitionWrapper wsdlImplementativoErogatore;
  95.     /** WSDL Implementativo fruitore */
  96.     private DefinitionWrapper wsdlImplementativoFruitore;
  97.     /** WSDL logico erogatore */
  98.     private DefinitionWrapper wsdlLogicoErogatore;
  99.     /** WSDL logico fruitore */
  100.     private DefinitionWrapper wsdlLogicoFruitore;
  101.     /** WSDL Concettuale */
  102.     private DefinitionWrapper wsdlConcettuale;
  103.     /** Schemi */
  104.     private List<SchemaXSDAccordoServizio> schemiErogatore = new ArrayList<SchemaXSDAccordoServizio>();
  105.     private List<SchemaXSDAccordoServizio> schemiFruitore = new ArrayList<SchemaXSDAccordoServizio>();
  106.     private List<String> schemiNames = new ArrayList<>();
  107.     /** Import degli schemi (xsd) */
  108.     private List<Schema> importsSchemiErogatore = new ArrayList<Schema>();
  109.     private List<Schema> importsSchemiFruitore = new ArrayList<Schema>();
  110.     /** Import  (wsdl) */
  111.     private List<Import> importsWsdlErogatore = new ArrayList<Import>();
  112.     private List<Import> importsWsdlFruitore = new ArrayList<Import>();
  113.     /** Directory dove vengono salvati gli schemi */
  114.     private TipoSchemaXSDAccordoServizio tipoSchema = TipoSchemaXSDAccordoServizio.ALLEGATO;
  115.     /** Il booleano gestisciNomi indica se, in caso di conflitti di nomi, questi vengono automaticamente risolti
  116.      * o venga lanciata un'eccezione dai metodi. */
  117.     private boolean gestisciNomi;
  118.    

  119.    
  120.     /* ------- ALTRO ---------- */
  121.     private MessageXMLUtils xmlUtils = null;
  122.     private WSDLUtilities wsdlUtilities = null;
  123.    
  124.    
  125.    
  126.    
  127.    
  128.     /* ------- Costruttori --------- */
  129.    
  130.     /**
  131.      * Suddivide un wsdl erogatore.
  132.      *
  133.      * Tutti i documenti inclusi dai wsdl (via import o include) sono recuperati per essere
  134.      * ricopiati nella cartella schemiDir (di default "allegati") e gli attributi di location
  135.      * aggiornati di conseguenza. In caso di conflitti di nomi, questi vengono automaticamente risolti.
  136.      *
  137.      * Gli schema vengono estratti e copiati come xsd  nella cartella schemiDir ed inclusi nel documento
  138.      * originale via xsd:include/xsd:import.
  139.      *
  140.      * @param wsdlErogatore
  141.      * @throws SplitWSDLException
  142.      */
  143.     public SplitWSDL(String wsdlErogatore) throws SplitWSDLException{
  144.         this(wsdlErogatore, null, null, null, null, null, TipoSchemaXSDAccordoServizio.ALLEGATO, true, false);
  145.     }
  146.     public SplitWSDL(String wsdlErogatore,boolean permettiSchemaLocationNonDefiniti) throws SplitWSDLException{
  147.         this(wsdlErogatore, null, null, null, null, null, TipoSchemaXSDAccordoServizio.ALLEGATO, true,permettiSchemaLocationNonDefiniti);
  148.     }
  149.    
  150.    
  151.     /**
  152.      * Suddivide i wsdl erogatore e fruitore.
  153.      *
  154.      * Tutti i documenti inclusi dai wsdl (via import o include) sono recuperati per essere
  155.      * ricopiati nella cartella schemiDir (di default "allegati") e gli attributi di location
  156.      * aggiornati di conseguenza. In caso di conflitti di nomi, questi vengono automaticamente risolti.
  157.      *
  158.      * Gli schema vengono estratti e copiati come xsd  nella cartella schemiDir ed inclusi nel documento
  159.      * originale via xsd:include/xsd:import.
  160.      *
  161.      * I documenti inclusi da entrambi i wsdl vengono riconosciuti e copiati una sola volta tra gli schemi
  162.      *
  163.      * @param wsdlErogatore
  164.      * @param wsdlFruitore
  165.      * @throws SplitWSDLException
  166.      */
  167.    
  168.     public SplitWSDL(String wsdlErogatore, String wsdlFruitore) throws SplitWSDLException{
  169.         this(wsdlErogatore, wsdlFruitore, null, null, null, null, TipoSchemaXSDAccordoServizio.ALLEGATO, true, false);
  170.     }
  171.    
  172.    
  173.     /**
  174.      * Suddivide i wsdl erogatore e fruitore.
  175.      *
  176.      * Tutti i documenti inclusi dai wsdl (via import o include) sono recuperati per essere
  177.      * ricopiati nella cartella schemiDir (di default "allegati") e gli attributi di location
  178.      * aggiornati di conseguenza.
  179.      *
  180.      * Il booleano gestisciNomi indica se, in caso di conflitti di nomi, questi vengono automaticamente risolti
  181.      * o venga lanciata un'eccezione.
  182.      *
  183.      * Gli schema vengono estratti e copiati come xsd  nella cartella schemiDir ed inclusi nel documento
  184.      * originale via xsd:include.
  185.      *
  186.      * I documenti inclusi da entrambi i wsdl vengono riconosciuti e copiati una sola volta tra gli schemi
  187.      *
  188.      * @param wsdlErogatore
  189.      * @param wsdlFruitore
  190.      * @param gestisciNomi
  191.      * @throws SplitWSDLException
  192.      */

  193.     public SplitWSDL(String wsdlErogatore, String wsdlFruitore, boolean gestisciNomi) throws SplitWSDLException{
  194.         this(wsdlErogatore, wsdlFruitore, null, null, null, null, TipoSchemaXSDAccordoServizio.ALLEGATO, true, false);
  195.     }
  196.     public SplitWSDL(String wsdlErogatore, String wsdlFruitore, boolean gestisciNomi,boolean permettiSchemaLocationNonDefiniti) throws SplitWSDLException{
  197.         this(wsdlErogatore, wsdlFruitore, null, null, null, null, TipoSchemaXSDAccordoServizio.ALLEGATO, true, permettiSchemaLocationNonDefiniti);
  198.     }
  199.    
  200.     /**
  201.      * Suddivide i wsdl erogatore e fruitore.
  202.      *
  203.      * Tutti i documenti inclusi dai wsdl (via import o include) sono recuperati per essere
  204.      * ricopiati nella cartella schemiDir e gli attributi di location
  205.      * aggiornati di conseguenza. In caso di conflitti di nomi, questi vengono automaticamente risolti.
  206.      *
  207.      * Gli schema vengono estratti e copiati come xsd  nella cartella schemiDir ed inclusi nel documento
  208.      * originale via xsd:include.
  209.      *
  210.      * I documenti inclusi da entrambi i wsdl vengono riconosciuti e copiati una sola volta tra gli schemi
  211.      *
  212.      * @param wsdlErogatore
  213.      * @param wsdlFruitore
  214.      * @param tipoSchema
  215.      * @throws SplitWSDLException
  216.      */
  217.     public SplitWSDL(String wsdlErogatore, String wsdlFruitore, TipoSchemaXSDAccordoServizio tipoSchema) throws SplitWSDLException{
  218.         this(wsdlErogatore, wsdlFruitore, null, null, null, null, tipoSchema, true, false);
  219.     }
  220.     public SplitWSDL(String wsdlErogatore, String wsdlFruitore, TipoSchemaXSDAccordoServizio tipoSchema,boolean permettiSchemaLocationNonDefiniti) throws SplitWSDLException{
  221.         this(wsdlErogatore, wsdlFruitore, null, null, null, null, tipoSchema, true, permettiSchemaLocationNonDefiniti);
  222.     }
  223.    
  224.     /**
  225.      * Suddivide un wsdl.
  226.      *
  227.      * Tutti i documenti inclusi dai wsdl (via import o include) sono recuperati per essere
  228.      * ricopiati nella cartella schemiDir e gli attributi di location
  229.      * aggiornati di conseguenza. In caso di conflitti di nomi, questi vengono automaticamente risolti.
  230.      *
  231.      * Gli schema vengono estratti e copiati come xsd  nella cartella schemiDir ed inclusi nel documento
  232.      * originale via xsd:include.
  233.      *
  234.      * Il booleano gestisciNomi indica se, in caso di conflitti di nomi, questi vengono automaticamente risolti
  235.      * o venga lanciata un'eccezione.
  236.      *
  237.      * I documenti inclusi da entrambi i wsdl vengono riconosciuti e copiati una sola volta tra gli schemi
  238.      *
  239.      */
  240.     public SplitWSDL(String wsdl, String[] porttypesErogatore,String[] operationPorttypesErogatore, TipoSchemaXSDAccordoServizio tipoSchema, boolean gestisciNomi) throws SplitWSDLException{
  241.         this(wsdl, null, porttypesErogatore, operationPorttypesErogatore, null, null, tipoSchema, gestisciNomi,false);
  242.     }
  243.     public SplitWSDL(String wsdl, String[] porttypesErogatore,String[] operationPorttypesErogatore,
  244.             String[] porttypesFruitore,String[] operationPorttypesFruitore, TipoSchemaXSDAccordoServizio tipoSchema, boolean gestisciNomi) throws SplitWSDLException{
  245.         this(wsdl, wsdl, porttypesErogatore, operationPorttypesErogatore, porttypesFruitore, operationPorttypesFruitore, tipoSchema, gestisciNomi,false);
  246.     }
  247.     public SplitWSDL(String wsdl, String[] porttypesErogatore,String[] operationPorttypesErogatore,
  248.             String[] porttypesFruitore,String[] operationPorttypesFruitore, TipoSchemaXSDAccordoServizio tipoSchema, boolean gestisciNomi,boolean permettiSchemaLocationNonDefiniti) throws SplitWSDLException{
  249.         this(wsdl, wsdl, porttypesErogatore, operationPorttypesErogatore, porttypesFruitore, operationPorttypesFruitore, tipoSchema, gestisciNomi,permettiSchemaLocationNonDefiniti);
  250.     }
  251.    
  252.     private SplitWSDL(String wsdlErogatore, String wsdlFruitore, String[] porttypesErogatore,String[] operationPorttypesErogatore,
  253.             String[] porttypesFruitore,String[] operationPorttypesFruitore, TipoSchemaXSDAccordoServizio tipoSchema,
  254.             boolean gestisciNomi,boolean permettiSchemaLocationNonDefiniti) throws SplitWSDLException{
  255.        
  256.         this.gestisciNomi = gestisciNomi;
  257.         this.tipoSchema = tipoSchema;
  258.        
  259.        
  260.         /** Controllo che le informazioni passate siano consistenti */
  261.        
  262.         if(wsdlErogatore==null){
  263.             throw new SplitWSDLException("WSDL Erogatore non fornito");
  264.         }
  265.         if(porttypesErogatore!=null && operationPorttypesErogatore==null){
  266.             throw new SplitWSDLException("Operations dei PortyTypes per il wsdl erogatore non forniti");
  267.         }
  268.         if(porttypesErogatore!=null && porttypesErogatore.length!=operationPorttypesErogatore.length){
  269.             throw new SplitWSDLException("Operations ["+operationPorttypesErogatore.length+"] dei PortyTypes ["+porttypesErogatore.length+"] per il wsdl erogatore non correlate correttamente ai port types");
  270.         }
  271.         if(porttypesFruitore!=null){
  272.             if(operationPorttypesFruitore==null){
  273.                 throw new SplitWSDLException("Operations dei PortyTypes per il wsdl fruitore non forniti");
  274.             }
  275.             if(porttypesFruitore.length!=operationPorttypesFruitore.length){
  276.                 throw new SplitWSDLException("Operations ["+operationPorttypesFruitore.length+"] dei PortyTypes ["+porttypesFruitore.length+"] per il wsdl fruitore non correlate correttamente ai port types");
  277.             }
  278.         }
  279.        
  280.         this.porttypesErogatore = porttypesErogatore;
  281.         this.porttypesFruitore = porttypesFruitore;
  282.         this.operationPorttypesErogatore = operationPorttypesErogatore;
  283.         this.operationPorttypesFruitore = operationPorttypesFruitore;
  284.        
  285.         try{
  286.        
  287.             this.xmlUtils = MessageXMLUtils.DEFAULT;
  288.             this.wsdlUtilities = WSDLUtilities.getInstance(this.xmlUtils);
  289.            
  290.             /** Carico i wsdl necessari */
  291.             if (wsdlErogatore!= null) {
  292.                 this.wsdlErogatorePath = wsdlErogatore;
  293.                 this.wsdlErogatore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlErogatore),this.xmlUtils);
  294.                 this.wsdlConcettuale = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlErogatore),this.xmlUtils);
  295.                 this.wsdlLogicoErogatore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlErogatore),this.xmlUtils);
  296.                 this.wsdlImplementativoErogatore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlErogatore),this.xmlUtils);
  297.             }
  298.            
  299.             if (wsdlFruitore!= null) {
  300.                 this.wsdlFruitorePath = wsdlFruitore;
  301.                 this.wsdlFruitore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlFruitore),this.xmlUtils);
  302.                 this.wsdlLogicoFruitore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlFruitore),this.xmlUtils);
  303.                 this.wsdlImplementativoFruitore = new DefinitionWrapper(this.wsdlUtilities.readWSDLFromLocation(wsdlFruitore),this.xmlUtils);
  304.             }
  305.            
  306.             /** Costruisco tutti i partizionamenti **/
  307.             creaSchemi(permettiSchemaLocationNonDefiniti);
  308.             creaConcettuale();
  309.             creaLogicoErogatore();
  310.             creaImplementativoErogatore();
  311.             if(wsdlFruitore==null || (porttypesErogatore!= null && porttypesFruitore==null)) return;
  312.             creaLogicoFruitore();
  313.             creaImplementativoFruitore();
  314.            
  315.         }catch(Exception e){
  316.             throw new SplitWSDLException(e.getMessage(),e);
  317.         }
  318.     }
  319.    
  320.    
  321.    
  322.    
  323.    
  324.    
  325.    
  326.    
  327.    
  328.    
  329.    
  330.     /* ------------------ Metodi pubblici ----------------------- */
  331.    
  332.     /**
  333.      * METODI PER LA SCRITTURA SU FS DEI DOCUMENTI
  334.      *
  335.      * @param dir Directory dove produrre i documenti
  336.      * @throws IOException
  337.      * @throws WSDLException
  338.      * @throws TransformerException
  339.      * @throws TransformerFactoryConfigurationError
  340.      * @throws ParserConfigurationException
  341.      * @throws XMLException
  342.      */
  343.     public void writeTo(File dir,boolean prettyPrint) throws WSDLException, IOException, TransformerException,
  344.         ParserConfigurationException, TransformerFactoryConfigurationError, org.openspcoop2.utils.wsdl.WSDLException, XMLException{
  345.         writeSchemiTo(dir,prettyPrint);
  346.         // Creo il folder per le interfacce
  347.         File interfacce = new File(dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_INTERFACCE);
  348.         interfacce.mkdir();
  349.         writeConcettualeTo(dir,prettyPrint);
  350.         writeLogicoErogatoreTo(dir,prettyPrint);
  351.         writeLogicoFruitoreTo(dir,prettyPrint);
  352.         File implementativi = new File(dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_IMPLEMENTATIVI);
  353.         implementativi.mkdir();
  354.         writeImplementativoErogatoreTo(dir,prettyPrint);
  355.         writeImplementativoFruitoreTo(dir,prettyPrint);
  356.     }
  357.    
  358.     public DefinitionWrapper getWsdlImplementativoErogatore() {
  359.         return this.wsdlImplementativoErogatore;
  360.     }
  361.     public DefinitionWrapper getWsdlImplementativoFruitore() {
  362.         return this.wsdlImplementativoFruitore;
  363.     }
  364.     public DefinitionWrapper getWsdlLogicoErogatore() {
  365.         return this.wsdlLogicoErogatore;
  366.     }
  367.     public DefinitionWrapper getWsdlLogicoFruitore() {
  368.         return this.wsdlLogicoFruitore;
  369.     }
  370.     public DefinitionWrapper getWsdlConcettuale() {
  371.         return this.wsdlConcettuale;
  372.     }
  373.     public List<SchemaXSDAccordoServizio> getSchemiErogatore() {
  374.         return this.schemiErogatore;
  375.     }
  376.     public List<SchemaXSDAccordoServizio> getSchemiFruitore() {
  377.         return this.schemiFruitore;
  378.     }
  379.    
  380.    
  381.    
  382.    
  383.    
  384.    
  385.    
  386.    
  387.    
  388.    
  389.    
  390.     /* ------------------- SCHEMI ----------------------------- */
  391.    
  392.     /**
  393.      * Trasferisce tutti i documenti inclusi e importati in un'unica cartella (schemaLocation)
  394.      * Prepara i wsdl:import da sostuituire agli schema del wsdl:types nel wsdlErogatore e wsdlFruitore
  395.      *
  396.      * @throws TransformerException
  397.      * @throws SchemaXSDNamingException
  398.      * @throws ParserConfigurationException
  399.      * @throws SAXException
  400.      * @throws IOException
  401.      * @throws XMLException
  402.      */
  403.     @SuppressWarnings("unchecked")
  404.     private void creaSchemi(boolean permettiSchemaLocationNonDefiniti) throws TransformerException, SchemaXSDNamingException, ParserConfigurationException, SAXException, IOException, XMLException{
  405.         // Mi serve per non ricominciare la numerazione degli schemi da 0 quando li produco per il fruitore
  406.         int flag = 0;
  407.        
  408.         flag = gestisciImportInclude(this.wsdlErogatore, this.wsdlErogatorePath,
  409.                 this.schemiErogatore, this.importsSchemiErogatore, this.importsWsdlErogatore, true, flag,permettiSchemaLocationNonDefiniti);
  410.        
  411.         /** Se la sorgente e' unica, non importa gestire nuovi import/include per il wsdlFruitore. E' lo stesso, verrebbero solo duplicati */
  412.         if(this.porttypesErogatore!=null){
  413.             this.schemiFruitore = (ArrayList<SchemaXSDAccordoServizio>) ((ArrayList<SchemaXSDAccordoServizio>) this.schemiErogatore).clone();
  414.             this.importsSchemiFruitore = (ArrayList<Schema>) ((ArrayList<Schema>)this.importsSchemiErogatore).clone();
  415.             this.importsWsdlFruitore = (ArrayList<Import>) ((ArrayList<Import>)this.importsWsdlErogatore).clone();
  416.         } else {
  417.             flag = gestisciImportInclude(this.wsdlFruitore, this.wsdlFruitorePath, this.schemiFruitore, this.importsSchemiFruitore, this.importsWsdlFruitore, false, flag, permettiSchemaLocationNonDefiniti);
  418.         }
  419.        
  420.     }
  421.    
  422.     @SuppressWarnings("unchecked")
  423.     private int gestisciImportInclude(DefinitionWrapper input_wsdl, String input_wsdlPath,
  424.             List<SchemaXSDAccordoServizio> output_schemi, List<Schema> output_importsSchemi,List<Import> output_importsWsdl,
  425.             boolean isErogatore, int flag, boolean permettiSchemaLocationNonDefiniti) throws ParserConfigurationException, SAXException, IOException, SchemaXSDNamingException, XMLException {
  426.         int ritorno = 0;
  427.         if(input_wsdl==null) return ritorno;
  428.        
  429.         /** Schemi XSD */
  430.         if(input_wsdl.getTypes()!=null){
  431.             List<?> schemas = input_wsdl.getTypes().getExtensibilityElements();
  432.             //Controllo se ci sono xsd:Schema dentro i types
  433.             if(schemas!=null){
  434.                 for(int i=0; i<schemas.size(); i++){
  435.                     Schema schema = (Schema) schemas.get(i);
  436.                     String targetNamespace = schema.getElement().getAttribute("targetNamespace");
  437.                    
  438.                     // Prendo la lista dei namespace dichiarati nel wsdl
  439.                     Map<String,String> definitionNamespace = input_wsdl.getWsdlDefinition().getNamespaces();
  440.                     Set<String> prefixes = definitionNamespace.keySet();
  441.                     Iterator<String> it = prefixes.iterator();
  442.                     while(it.hasNext()){
  443.                         String prefix = it.next();
  444.                         if(prefix.equals("")){
  445.                             if(schema.getElement().getAttribute("xmlns").equals(""))
  446.                                 schema.getElement().setAttribute("xmlns", definitionNamespace.get(prefix));
  447.                         }
  448.                         else {
  449.                             if(schema.getElement().getAttribute("xmlns:"+prefix).equals(""))
  450.                                 schema.getElement().setAttribute("xmlns:"+prefix, definitionNamespace.get(prefix));
  451.                         }
  452.                     }
  453.                    
  454.                     // Cerco un nome per l'xsd che vado a creare
  455.                     String filename = getLocalNameSchema(SplitWSDL.DEFINITORIO_FILENAME, output_schemi, false);
  456.                    
  457.                     // Gli XSDSchema devono essere integrati con il costrutto xsd:include
  458.                     Element newSchemaElement = schema.getElement().getOwnerDocument().createElementNS("http://www.w3.org/2001/XMLSchema", "xsd:schema");
  459.                     newSchemaElement.setAttribute("targetNamespace", targetNamespace);
  460.                    
  461.                     Element include = schema.getElement().getOwnerDocument().createElementNS("http://www.w3.org/2001/XMLSchema", "xsd:include");
  462.                     include.setAttribute("schemaLocation", ".." + File.separator + this.tipoSchema.getDirectory() + File.separator + filename);
  463.                    
  464.                     newSchemaElement.appendChild(include);
  465.                     Schema newSchema = new SchemaImpl();
  466.                     newSchema.setElement(newSchemaElement);
  467.                     newSchema.setElementType(schema.getElementType());
  468.                     newSchema.setRequired(schema.getRequired());
  469.                    
  470.                     output_importsSchemi.add(newSchema);
  471.                    
  472.                     /// Aggiungo lo schema tra gli schemi
  473.                     if(isErogatore)
  474.                         addSchemaErogatore(schema.getElement(),filename, new File(input_wsdlPath), false, permettiSchemaLocationNonDefiniti);
  475.                     else
  476.                         addSchemaFruitore(schema.getElement(), filename, new File(input_wsdlPath), false, permettiSchemaLocationNonDefiniti);
  477.                     ritorno ++;
  478.                 }
  479.             }
  480.         }
  481.        
  482.         /** WSDL imports */
  483.         // Controllo se ci sono wsdl:import
  484.         Map<?,?> importsMap = input_wsdl.getImports();
  485.         Iterator<?> namespaces = importsMap.values().iterator();
  486.         while(namespaces.hasNext()){
  487.             List<?> imports = (List<?>) namespaces.next();
  488.             for(int i = 0; i<imports.size(); i++){
  489.                
  490.                 Import myimport = (Import) imports.get(i);
  491.                 String location = myimport.getLocationURI();
  492.                
  493.                 File importedFile = new File(new File(input_wsdlPath).getParentFile(), location);
  494.                
  495.                 String schemaFilename = getLocalNameSchema(importedFile, output_schemi, false);
  496.                
  497.                 /** Creo il wsdl:import **/
  498.                 Import newImport = input_wsdl.createImport();
  499.                 newImport.setLocationURI(".." + File.separator + this.tipoSchema.getDirectory() + File.separator + schemaFilename);
  500.                 newImport.setNamespaceURI(myimport.getNamespaceURI());
  501.                 output_importsWsdl.add(newImport);
  502.                
  503.                 /** Aggiungo il documento importato alla lista degli schemi */
  504.                 org.openspcoop2.message.xml.MessageXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;
  505.                 Document doc = xmlUtils.newDocument(importedFile);
  506.                 if(isErogatore)
  507.                     addSchemaErogatore(doc.getDocumentElement(), schemaFilename, importedFile, true, permettiSchemaLocationNonDefiniti);
  508.                 else
  509.                     addSchemaFruitore(doc.getDocumentElement(), schemaFilename, importedFile, true, permettiSchemaLocationNonDefiniti);
  510.             }
  511.         }
  512.         return ritorno;
  513.     }
  514.    
  515.     /**
  516.      * Ottiene un nome da usare per lo schema.
  517.      * Se il file e' nuovo in lista ed il suo nome univoco, viene mantenuto.
  518.      * Se il file e' gia' incluso in lista, gli viene dato lo stesso nome.
  519.      * Se il file e' nuovo in lista, ma il nome gia' usato, viene aggiunto e rinominato.
  520.      *
  521.      * @param file Documento da aggiungere
  522.      * @param lista Lista degli schemi
  523.      * @param force indica se forzare l'uso del nome originale o meno.
  524.      *
  525.      * @return nome da usare per lo schema.
  526.      * @throws SchemaXSDNamingException
  527.      */
  528.     private String getLocalNameSchema (File file, List<SchemaXSDAccordoServizio> lista, boolean force) throws SchemaXSDNamingException{
  529.         String name =  getLocalNameSchema(file, null, lista, force, true);
  530.         this.schemiNames.add(name);
  531.         return name;
  532.     }
  533.    
  534.     /**
  535.      * Ottiene un nome da usare per lo schema.
  536.      * Se il file e' nuovo in lista ed il suo nome univoco, viene mantenuto.
  537.      * Se il file e' gia' incluso in lista, gli viene dato lo stesso nome.
  538.      * Se il file e' nuovo in lista, ma il nome gia' usato, viene aggiunto e rinominato.
  539.      *
  540.      * @param filename nome del file da aggiungere
  541.      * @param lista Lista degli schemi
  542.      * @param force indica se forzare l'uso del nome originale o meno.
  543.      *
  544.      * @return nome da usare per lo schema.
  545.      * @throws SchemaXSDNamingException
  546.      */
  547.     private String getLocalNameSchema (String filename, List<SchemaXSDAccordoServizio> lista, boolean force) throws SchemaXSDNamingException{
  548.         String name = getLocalNameSchema(null, filename, lista, force, true);
  549.         this.schemiNames.add(name);
  550.         return name;
  551.     }
  552.    
  553.     /**
  554.      * Ottiene un nome da usare per lo schema.
  555.      * Se il file e' nuovo in lista ed il suo nome univoco, viene mantenuto.
  556.      * Se il file e' gia' incluso in lista, gli viene dato lo stesso nome.
  557.      * Se il file e' nuovo in lista, ma il nome gia' usato, viene aggiunto e rinominato.
  558.      *
  559.      * Per gli schemi creati a partire dagli schemi definiti nel wsdl originale, file sara' a null mentre filename viene valorizzato.
  560.      *
  561.      * @param file
  562.      * @param filename
  563.      * @param lista
  564.      * @param force
  565.      * @param firstTime
  566.      * @return nome da usare per lo schema.
  567.      * @throws SchemaXSDNamingException
  568.      */
  569.     private String getLocalNameSchema (File file, String filename, List<SchemaXSDAccordoServizio> lista, boolean force, boolean firstTime) throws SchemaXSDNamingException{

  570.         if(force){
  571.             if(file!=null)
  572.                 return file.getName();
  573.             else
  574.                 return filename;
  575.         }
  576.                
  577.         // Scorro la lista
  578.         // Controllo (solo la prima volta) Se il file e' gia in lista
  579.         if(firstTime && file!=null){
  580.             for(int i=0;i<lista.size(); i++){
  581.                 if(file.getAbsolutePath().compareTo(lista.get(i).getSourceAbsolutePath()) == 0) return lista.get(i).getFilename();
  582.             }
  583.         }
  584.         if(lista.equals(this.schemiFruitore) && file!=null){
  585.             //Il documento potrebbe gia' esser stato importato dal wsdlErogatore.
  586.             //In questo caso devo importarlo con lo stesso nome assegnato in precedenza.
  587.             for(int i=0;i<this.schemiErogatore.size(); i++){
  588.                 if(file.getAbsolutePath().compareTo(this.schemiErogatore.get(i).getSourceAbsolutePath()) == 0){
  589.                     return this.schemiErogatore.get(i).getFilename();
  590.                 }
  591.             }
  592.         }
  593.        
  594.         if(filename==null)
  595.             filename = file.getName();
  596.        
  597.         for(int i=0;i<this.schemiNames.size(); i++){
  598.             // Se c'e' gia un file con quel nome in lista
  599.             if(filename.compareTo(this.schemiNames.get(i)) == 0) {
  600.                 // Se c'e' la gestione dei nomi doppi
  601.                 if(this.gestisciNomi){
  602.                     // Prendo il nome del file lo nomino filename_X.ext , dove X e' un intero
  603.                     int punto = filename.lastIndexOf(".");
  604.                     String filenameSenzaExt = filename.substring(0, punto);
  605.                     String filenameExt = filename.substring(punto);
  606.                     int underscore = filename.lastIndexOf("_");
  607.                     if(underscore<0){
  608.                         filename = filenameSenzaExt + "_0" + filenameExt;
  609.                     }
  610.                     else {
  611.                         try{
  612.                             int number = Integer.parseInt(filenameSenzaExt.substring(underscore+1));
  613.                             filename = filenameSenzaExt.substring(0, underscore+1) + (number + 1) + filenameExt;
  614.                         } catch (Exception e) {
  615.                             filename = filenameSenzaExt + "_0" + filenameExt;
  616.                         }
  617.                     }
  618.                     // Controllo l'univocita' del nuovo nome di file
  619.                     if(file!=null)
  620.                         return getLocalNameSchema(new File(file.getParentFile(),filename), lista, false);
  621.                     else
  622.                         return getLocalNameSchema(filename, lista, false);
  623.                 }
  624.                 else {
  625.                     throw new SchemaXSDNamingException("Ci sono due documenti inclusi/importati che hanno lo stesso nome di file: " + filename);
  626.                 }
  627.             }
  628.         }
  629.         return filename;
  630.     }
  631.    
  632.     /**
  633.      * Aggiunge lo schema all'array dell'Erogatore.
  634.      *
  635.      *
  636.      * @param Element del documento importato o incluso
  637.      * @param Nome del file con cui verra' salvato il documento passato
  638.      * @param Riferimento al documento che ha incluso/importato
  639.      * @param Controlla se il file e' gia' stato incluso
  640.      * @throws ParserConfigurationException
  641.      * @throws SAXException
  642.      * @throws IOException
  643.      * @throws SchemaXSDNamingException
  644.      * @throws XMLException
  645.      */
  646.     private void addSchemaErogatore(Element xml, String filename, File localpath,
  647.             boolean check, boolean permettiSchemaLocationNonDefiniti) throws ParserConfigurationException, SAXException, IOException, SchemaXSDNamingException, XMLException{
  648.         addSchema(xml, filename, localpath, this.schemiErogatore, check, permettiSchemaLocationNonDefiniti);
  649.     }
  650.    
  651.     /**
  652.      * Aggiunge lo schema all'array del Fruitore
  653.      *
  654.      *
  655.      * @param Element del documento importato o incluso
  656.      * @param Nome del file con cui verra' salvato il documento passato
  657.      * @param Riferimento al documento che ha incluso/importato
  658.      * @param Controlla se il file e' gia' stato incluso
  659.      * @throws ParserConfigurationException
  660.      * @throws SAXException
  661.      * @throws IOException
  662.      * @throws SchemaXSDNamingException
  663.      * @throws XMLException
  664.      */
  665.     private void addSchemaFruitore(Element xml, String filename, File localpath,
  666.             boolean check, boolean permettiSchemaLocationNonDefiniti) throws ParserConfigurationException, SAXException, IOException, SchemaXSDNamingException, XMLException{
  667.         addSchema(xml, filename, localpath, this.schemiFruitore, check, permettiSchemaLocationNonDefiniti);
  668.     }
  669.    
  670.     /**
  671.      * Prende il documento xml passato, cerca eventuali include o import per iterare la procedura, modifica opportunamente
  672.      * i valori dei location e schemaLocation, aggiunge uno schema alla lista passata.
  673.      *
  674.      * @param Element del documento importato o incluso
  675.      * @param Nome del file con cui verra' salvato il documento passato
  676.      * @param Riferimento al documento
  677.      * @param Lista in cui aggiungere lo schema
  678.      * @throws ParserConfigurationException
  679.      * @throws SAXException
  680.      * @throws IOException
  681.      * @throws SchemaXSDNamingException
  682.      * @throws XMLException
  683.      */
  684.     private void addSchema(Element xml, String filename, File xmlSource, List<SchemaXSDAccordoServizio> schemi,
  685.             boolean check, boolean permettiSchemaLocationNonDefiniti) throws ParserConfigurationException, SAXException, IOException, SchemaXSDNamingException, XMLException{
  686.        
  687.         org.openspcoop2.message.xml.MessageXMLUtils xmlUtils = org.openspcoop2.message.xml.MessageXMLUtils.DEFAULT;
  688.                
  689.         // Indica se il filename deve essere forzato ad essere quello indicato
  690.         boolean force = false;
  691.         // Devo controllare se questo schema e' gia' nella lista. In tal caso esco.
  692.         if(check){
  693.             for(int i=0;i<schemi.size(); i++){
  694.                 if(xmlSource.getAbsolutePath().compareTo(schemi.get(i).getSourceAbsolutePath()) == 0) return;
  695.             }
  696.         }
  697.        
  698.         // Cerco gli xs:import
  699.         NodeList nl = xml.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "import");
  700.         for(int i = 0; i<nl.getLength(); i++){
  701.             // Trovato un xsd:import. prendo lo schemaLocation
  702.             String schemaLocation = ((Element) nl.item(i)).getAttribute("schemaLocation");
  703.             if(schemaLocation==null || "".equals(schemaLocation)){
  704.                 if(!permettiSchemaLocationNonDefiniti){
  705.                     // Lo schema location non è presente ad esempio quando si costruisce un unico file wsdl+xsd,
  706.                     // e tutti gli xsd sono all'interno del wsdl. E' presente l'import ma non lo schema location
  707.                     throw new ParserConfigurationException("attributo 'schemaLocation' non definito in import (file "+filename+")");
  708.                 }
  709.             }
  710.             else{
  711.                 // Prendo il file in questione
  712.                 File schema = new File(xmlSource.getParentFile() ,schemaLocation);
  713.                 String schemaFilename = getLocalNameSchema(schema,schemi, force);
  714.                 // Cambio lo schemaLocation con il path locale.
  715.                 ((Element) nl.item(i)).setAttribute("schemaLocation",schemaFilename);
  716.                
  717.                 // Aggiungo il documento nella lista degli schemi
  718.                 Document doc = xmlUtils.newDocument(schema);
  719.                 addSchema(doc.getDocumentElement(), schemaFilename, schema, schemi, true, permettiSchemaLocationNonDefiniti);
  720.             }
  721.         }
  722.         // Cerco gli xs:include
  723.         nl = xml.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "include");
  724.         for(int i = 0; i<nl.getLength(); i++){
  725.             // Trovato un xsd:import. prendo lo schemaLocation
  726.             String schemaLocation = ((Element) nl.item(i)).getAttribute("schemaLocation");
  727.             if(schemaLocation==null || "".equals(schemaLocation)){
  728.                 if(!permettiSchemaLocationNonDefiniti){
  729.                     // Lo schema location non è presente ad esempio quando si costruisce un unico file wsdl+xsd,
  730.                     // e tutti gli xsd sono all'interno del wsdl. E' presente l'import ma non lo schema location
  731.                     throw new ParserConfigurationException("attributo 'schemaLocation' non definito in include (file "+filename+")");
  732.                 }
  733.             }
  734.             else{
  735.                 // Prendo il file in questione
  736.                 File schema = new File(xmlSource.getParentFile() ,schemaLocation);
  737.                 String schemaFilename = getLocalNameSchema(schema, schemi, force);
  738.                 // Cambio lo schemaLocation con il path locale.
  739.                 ((Element) nl.item(i)).setAttribute("schemaLocation",schemaFilename);
  740.                
  741.                 // Aggiungo il documento nella lista degli schemi
  742.                 Document doc = xmlUtils.newDocument(schema);
  743.                 addSchema(doc.getDocumentElement(), schemaFilename, schema, schemi, true, permettiSchemaLocationNonDefiniti);
  744.             }
  745.         }
  746.        
  747.         // Cerco i wsdl:import
  748.         nl = xml.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "import");
  749.         for(int i = 0; i<nl.getLength(); i++){
  750.             // Trovato un wsdl:import. prendo il location
  751.             String schemaLocation = ((Element) nl.item(i)).getAttribute("location");
  752.             if(schemaLocation==null || "".equals(schemaLocation)){
  753.                 if(!permettiSchemaLocationNonDefiniti){
  754.                     // Lo schema location non è presente ad esempio quando si costruisce un unico file wsdl+xsd,
  755.                     // e tutti gli xsd sono all'interno del wsdl. E' presente l'import ma non lo schema location
  756.                     throw new ParserConfigurationException("attributo 'location' non definito in include (file "+filename+")");
  757.                 }
  758.             }
  759.             else{
  760.                 // Prendo il file in questione
  761.                 File schema = new File(xmlSource.getParentFile() ,schemaLocation);
  762.                 String schemaFilename = getLocalNameSchema(schema, schemi, force);
  763.                 // Cambio lo schemaLocation con il path locale.
  764.                 ((Element) nl.item(i)).setAttribute("location", schemaFilename);
  765.                
  766.                 // Aggiungo il documento nella lista degli schemi
  767.                 Document doc = xmlUtils.newDocument(schema);
  768.                 addSchema(doc.getDocumentElement() , schemaFilename, schema, schemi, true, permettiSchemaLocationNonDefiniti);
  769.             }
  770.         }
  771.        
  772.         SchemaXSDAccordoServizio schema = new SchemaXSDAccordoServizio(xml, filename, xmlSource, this.tipoSchema);
  773.         schemi.add(schema);
  774.     }
  775.    
  776.     private void writeSchemiTo(File basedir,boolean prettyPrint) throws TransformerException, IOException, ParserConfigurationException, TransformerFactoryConfigurationError, XMLException{
  777.        
  778.         if((this.schemiErogatore.size() + this.schemiFruitore.size()) == 0) return;
  779.        
  780.         if(!basedir.isDirectory()) {
  781.             throw new IOException("Il path indicato non e' una directory valida.");
  782.         }
  783.        
  784.         for(int i=0; i< this.schemiErogatore.size(); i++){
  785.             this.schemiErogatore.get(i).writeTo(basedir,prettyPrint);
  786.         }
  787.        
  788.         for(int i=0; i< this.schemiFruitore.size(); i++){
  789.             this.schemiFruitore.get(i).writeTo(basedir,prettyPrint);
  790.         }
  791.     }
  792.    
  793.    
  794.    
  795.    
  796.    
  797.    
  798.    
  799.    
  800.    
  801.    
  802.    
  803.    
  804.    
  805.    
  806.    
  807.     /* ------------------- CONCETTUALI ----------------------------- */
  808.    
  809.     /**
  810.      * Crea un documento concettuale, contenente cioe' solo la definizione dei messaggi scambiati
  811.      * e la definizione astratta delle operazioni ammesse.
  812.      */
  813.     private void creaConcettuale ()
  814.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  815.        
  816.        
  817.         this.wsdlUtilities.removeAllBindings(this.wsdlConcettuale);
  818.         this.wsdlUtilities.removeAllServices(this.wsdlConcettuale);
  819.        
  820.         Types types = this.wsdlConcettuale.getTypes();
  821.         List<?> xsdTypes = types.getExtensibilityElements();
  822.         while (xsdTypes.size()>0){
  823.             types.removeExtensibilityElement((Schema) xsdTypes.get(0));
  824.             xsdTypes = types.getExtensibilityElements();
  825.         }
  826.        
  827.         //Sistemo gli imports:
  828.         this.wsdlConcettuale.removeAllImports();
  829.        
  830.         for(int i = 0; i<this.importsWsdlErogatore.size(); i++) {
  831.             this.wsdlConcettuale.addImport(this.importsWsdlErogatore.get(i));
  832.         }
  833.        
  834.         for(int i = 0; i<this.importsSchemiErogatore.size(); i++) {
  835.             this.wsdlConcettuale.getTypes().addExtensibilityElement(this.importsSchemiErogatore.get(i));
  836.         }
  837.        
  838.         // controllo se il documento importato era gia' tra quelli dell'erogatore
  839.         for(int i = 0; i<this.importsWsdlFruitore.size(); i++) {
  840.             boolean found = false;
  841.             for(int j = 0; j<this.importsWsdlErogatore.size(); j++) {
  842.                 if(this.importsWsdlErogatore.get(j).getLocationURI().compareTo(this.importsWsdlFruitore.get(i).getLocationURI()) == 0 &&
  843.                         this.importsWsdlErogatore.get(j).getNamespaceURI().compareTo(this.importsWsdlFruitore.get(i).getNamespaceURI()) == 0){
  844.                     found = true;
  845.                 }
  846.             }
  847.             if(!found) this.wsdlConcettuale.addImport(this.importsWsdlFruitore.get(i));
  848.         }
  849.        
  850.         // Controllo anche gli schemi importati.
  851.         for(int i = 0; i<this.importsSchemiFruitore.size(); i++) {
  852.             boolean found = false;
  853.             Element includeFruitore = (Element) this.importsSchemiFruitore.get(i).getElement().getFirstChild();
  854.            
  855.             for(int j = 0; j<this.importsSchemiErogatore.size(); j++) {
  856.                 Element includeErogatore = (Element) this.importsSchemiErogatore.get(j).getElement().getFirstChild();
  857.                 if(includeFruitore.getAttribute("schemaLocation").compareTo(includeErogatore.getAttribute("schemaLocation")) == 0){
  858.                     found = true;
  859.                 }
  860.             }
  861.             if(!found) this.wsdlConcettuale.getTypes().addExtensibilityElement(this.importsSchemiFruitore.get(i));
  862.         }


  863.         if (this.wsdlFruitore !=null){
  864.             // e' un concettuale, si aggiungono i portTypes, i messaggi ed eventuali namespace particolari
  865.             //namespace
  866.             Map<?,?> m = this.wsdlFruitore.getNamespaces();
  867.             Iterator<?> it = null;

  868.             m = this.wsdlFruitore.getMessages();
  869.             it = m.values().iterator();
  870.             while (it.hasNext()){
  871.                 Message im = (Message) it.next();
  872.                 this.wsdlConcettuale.addMessage(im);
  873.             }

  874.             m = this.wsdlFruitore.getAllPortTypes();
  875.             it = m.values().iterator();
  876.             while (it.hasNext()){
  877.                 PortType im = (PortType) it.next();
  878.                 this.wsdlConcettuale.addPortType(im);
  879.             }
  880.         }
  881.        
  882.         if(this.porttypesErogatore!=null){
  883.             String[] portTypes = merge(this.porttypesErogatore, this.porttypesFruitore);
  884.             /** PULIZIA PORT TYPE */
  885.             Map<?, ?> m = this.wsdlConcettuale.getAllPortTypes();
  886.             Iterator<?> it = m.values().iterator();
  887.             while (it.hasNext()){
  888.                 PortType now = (PortType) it.next();
  889.                 String cuBinName = now.getQName().getLocalPart();
  890.                 boolean delete = true;
  891.                 for(int i=0; i<portTypes.length;i++){
  892.                     String check = portTypes[i];
  893.                     if (check.equals(cuBinName))
  894.                     {
  895.                         delete = false;
  896.                         break;
  897.                     }
  898.                 }
  899.                 if (delete){
  900.                     this.wsdlConcettuale.removePortType(now.getQName());
  901.                 }
  902.             }

  903.             /** Pulizia message */
  904.             List<Message> mess = new ArrayList<Message>();
  905.             m = this.wsdlConcettuale.getAllPortTypes();
  906.             it = m.values().iterator();
  907.             while (it.hasNext()){
  908.                 PortType p = (PortType) it.next();
  909.                 List<?> myl = p.getOperations();
  910.                 //prelevo i messaggi che interessano le operazioni di questo porttype
  911.                 for (int h=0, k=myl.size(); h<k; h++){
  912.                     Operation operationWSDL = (Operation) myl.get(h);
  913.                     Message input = operationWSDL.getInput()== null? null : operationWSDL.getInput().getMessage();
  914.                     if (input !=null)
  915.                         mess.add(input);
  916.                     Message output = operationWSDL.getOutput() == null? null: operationWSDL.getOutput().getMessage();
  917.                     if (output !=null)
  918.                         mess.add(output);
  919.                 }
  920.             }

  921.             //rimuovo i messaggi non presenti nei porttype
  922.             m = this.wsdlConcettuale.getMessages();
  923.             it = m.values().iterator();
  924.             List<Message> removeM = new ArrayList<Message>();
  925.             while (it.hasNext()){
  926.                 Message temp = ((Message) it.next());
  927.                 if (!mess.contains(temp)){
  928.                     removeM.add(temp);
  929.                 }
  930.             }
  931.             for (int i=0, j=removeM.size(); i<j; i++){
  932.                 this.wsdlConcettuale.removeMessage(removeM.get(i).getQName());
  933.             }
  934.         }

  935.        
  936.        
  937.     }
  938.    
  939.     private void writeConcettualeTo(File dir,boolean prettyPrint) throws WSDLException, IOException, org.openspcoop2.utils.wsdl.WSDLException{
  940.         this.wsdlUtilities.writeWsdlTo(this.wsdlConcettuale,
  941.                 dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_INTERFACCE + File.separator + SplitWSDL.CONCETTUALE_FILENAME,
  942.                 prettyPrint);
  943.     }
  944.    
  945.    
  946.    
  947.    
  948.    
  949.    
  950.    
  951.    
  952.    
  953.    
  954.    
  955.    
  956.    
  957.    
  958.    
  959.    
  960.    
  961.    
  962.     /* ------------------- LOGICI ----------------------------- */
  963.    
  964.     private void creaLogicoErogatore()
  965.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  966.         creaLogico(this.wsdlLogicoErogatore, this.importsSchemiErogatore, this.importsWsdlErogatore, this.porttypesErogatore, this.operationPorttypesErogatore);
  967.     }
  968.    
  969.     private void creaLogicoFruitore()
  970.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  971.         if(this.wsdlLogicoFruitore==null) return;
  972.         creaLogico(this.wsdlLogicoFruitore, this.importsSchemiFruitore, this.importsWsdlFruitore, this.porttypesFruitore, this.operationPorttypesFruitore);
  973.     }
  974.    
  975.     private void creaLogico (DefinitionWrapper wsdlLogico, List<Schema> importsSchemi, List<Import> importsWsdl, String[] portTypes, String[] operations)
  976.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  977.        
  978.         //rimozione binding
  979.         Map<?,?> m = null;
  980.         Iterator<?> it = null;
  981.         this.wsdlUtilities.removeAllBindings(wsdlLogico);
  982.         this.wsdlUtilities.removeAllServices(wsdlLogico);
  983.         removeExtensibilityElements(wsdlLogico.getTypes());
  984.         for (int i=0; i<importsSchemi.size(); i++){
  985.             wsdlLogico.getTypes().addExtensibilityElement(importsSchemi.get(i));
  986.         }
  987.        
  988.         wsdlLogico.removeAllImports();
  989.         for (int i=0; i<importsWsdl.size(); i++){
  990.             wsdlLogico.addImport(importsWsdl.get(i));
  991.         }

  992.         //prelevo da un portType esistente prefix e namespace (necessari al QName)
  993.         m = wsdlLogico.getPortTypes();
  994.         it = m.values().iterator();
  995.         String prefix = null;
  996.         String namespace = null;
  997.         while (it.hasNext()){
  998.             PortType p = (PortType) it.next();
  999.             prefix = p.getQName().getPrefix();
  1000.             namespace = p.getQName().getNamespaceURI();
  1001.             break;
  1002.         }

  1003.         if (prefix == null && namespace == null)
  1004.         {
  1005.             throw new WSDLException(namespace, prefix);
  1006.         }

  1007.         //portType nulli, wsdl separati
  1008.         if (portTypes == null){
  1009.             return;
  1010.         }

  1011.         //riimposto i portType
  1012.         List<PortType> pts = new ArrayList<PortType>();

  1013.         for (int i=0, j=portTypes.length; i<j; i++){

  1014.             QName current = new QName(namespace, portTypes[i], prefix);
  1015.             PortType now = wsdlLogico.getPortType(current);
  1016.             String[] myops = operations[i] == null ? null: operations[i].split(",");
  1017.             if (myops == null)
  1018.             {
  1019.                 return;
  1020.             }
  1021.             //da tutte le operazioni di questo pt rimuovo quelle non interessanti
  1022.             List<?> opts = now.getOperations();
  1023.             Operation[] opp = new Operation[opts.size()];
  1024.             opts.toArray(opp);

  1025.             for (int x=0, y = opts.size(); x < y; x++)
  1026.             {
  1027.                 String cur = opp[x].getName();
  1028.                 boolean delete = true;
  1029.                 for (int h=0, k= myops.length; h < k; h++){
  1030.                     if (cur.equals(myops[h])){
  1031.                         delete = false;
  1032.                         break;
  1033.                     }
  1034.                 }
  1035.                 if (delete)
  1036.                     now.removeOperation(opp[x].getName(), null,null);

  1037.             }

  1038.             pts.add(now);
  1039.         }

  1040.         //in pts ho i portType filtrati come richiesto

  1041.         m = wsdlLogico.getAllPortTypes();
  1042.         it = m.values().iterator();

  1043.         //rimuovo tutti i portType
  1044.         while (it.hasNext()){
  1045.             it.next();
  1046.             it.remove();
  1047.             //def.removePortType(((PortType)it.next()).getQName());
  1048.         }

  1049.         List<Message> mess = new ArrayList<Message>();
  1050.         //inserisco quelli richiesti
  1051.         for (int i=0, j=pts.size(); i<j; i++){
  1052.             PortType p = pts.get(i);
  1053.             List<?> myl = p.getOperations();
  1054.             //prelevo i messaggi che interessano le operazioni di questo porttype
  1055.             for (int h=0, k=myl.size(); h<k; h++){
  1056.                 Operation operationWSDL = (Operation) myl.get(h);
  1057.                 Message input = operationWSDL.getInput()== null? null : operationWSDL.getInput().getMessage();
  1058.                 if (input !=null)
  1059.                     mess.add(input);
  1060.                 Message output = operationWSDL.getOutput() == null? null: operationWSDL.getOutput().getMessage();
  1061.                 if (output !=null)
  1062.                     mess.add(output);
  1063.             }
  1064.             wsdlLogico.addPortType(p);
  1065.         }

  1066.         //rimuovo i messaggi non presenti nei porttype

  1067.         m = wsdlLogico.getMessages();
  1068.         it = m.values().iterator();
  1069.         List<Message> removeM = new ArrayList<Message>();
  1070.         while (it.hasNext()){
  1071.             Message temp = ((Message) it.next());
  1072.             if (!mess.contains(temp))
  1073.                 removeM.add(temp);
  1074.         }

  1075.         for (int i=0, j=removeM.size(); i<j; i++){
  1076.             wsdlLogico.removeMessage(removeM.get(i).getQName());
  1077.         }

  1078.         /** PULIZIA PORT TYPE */
  1079.         m = wsdlLogico.getAllPortTypes();
  1080.         it = m.values().iterator();
  1081.         while (it.hasNext()){
  1082.             PortType now = (PortType) it.next();
  1083.             String cuBinName = now.getQName().getLocalPart();
  1084.             boolean delete = true;
  1085.             for(int i=0; i<portTypes.length;i++){
  1086.                 String check = portTypes[i];
  1087.                 //System.out.println("CONFRONTO ["+check+"] con ["+cuBinName+"]");
  1088.                 if (check.equals(cuBinName))
  1089.                 {
  1090.                     delete = false;
  1091.                     break;
  1092.                 }
  1093.             }
  1094.             if (delete){
  1095.                 wsdlLogico.removePortType(now.getQName());
  1096.             }
  1097.         }

  1098.     }
  1099.    
  1100.     private void writeLogicoErogatoreTo(File dir,boolean prettyPrint) throws WSDLException, IOException, org.openspcoop2.utils.wsdl.WSDLException{
  1101.         this.wsdlUtilities.writeWsdlTo(this.wsdlLogicoErogatore,
  1102.                 dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_INTERFACCE + File.separator + SplitWSDL.LOGICO_EROGATORE_FILENAME,
  1103.                 prettyPrint);
  1104.     }
  1105.    
  1106.     private void writeLogicoFruitoreTo(File dir,boolean prettyPrint) throws WSDLException, IOException, org.openspcoop2.utils.wsdl.WSDLException{
  1107.         this.wsdlUtilities.writeWsdlTo(this.wsdlLogicoFruitore,
  1108.                 dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_INTERFACCE + File.separator + SplitWSDL.LOGICO_FRUITORE_FILENAME,
  1109.                 prettyPrint);
  1110.     }
  1111.    
  1112.    
  1113.    
  1114.    
  1115.    
  1116.    
  1117.    
  1118.    
  1119.    
  1120.    
  1121.    
  1122.    
  1123.    
  1124.    
  1125.    
  1126.    
  1127.    
  1128.    
  1129.    
  1130.     /* ------------------- IMPLEMENTATIVI ----------------------------- */
  1131.    
  1132.     private void creaImplementativoErogatore()
  1133.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  1134.         Import logicoErogatore = this.wsdlImplementativoErogatore.createImport();
  1135.         logicoErogatore.setLocationURI(".." + File.separator + SplitWSDL.FOLDER_INTERFACCE + File.separator + SplitWSDL.LOGICO_EROGATORE_FILENAME);
  1136.         logicoErogatore.setNamespaceURI(this.wsdlLogicoErogatore.getTargetNamespace());
  1137.         creaImplementativo(this.wsdlImplementativoErogatore, logicoErogatore, this.porttypesErogatore, this.operationPorttypesErogatore);
  1138.     }
  1139.    
  1140.     private void creaImplementativoFruitore()
  1141.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  1142.         if(this.wsdlImplementativoFruitore==null) return;
  1143.         Import logicoFruitore = this.wsdlImplementativoFruitore.createImport();
  1144.         logicoFruitore.setLocationURI(".." + File.separator + SplitWSDL.FOLDER_INTERFACCE + File.separator + SplitWSDL.LOGICO_FRUITORE_FILENAME);
  1145.         logicoFruitore.setNamespaceURI(this.wsdlLogicoFruitore.getTargetNamespace());
  1146.         creaImplementativo(this.wsdlImplementativoFruitore, logicoFruitore, this.porttypesFruitore, this.operationPorttypesFruitore);
  1147.     }
  1148.    
  1149.     private void creaImplementativo (DefinitionWrapper wsdlImplementativo, Import logico, String[] portTypes, String[] operations)
  1150.     throws IOException, WSDLException,ParserConfigurationException,SAXException,IOException,TransformerException,TransformerConfigurationException{
  1151.        
  1152.         //rimozione messaggi

  1153.         this.wsdlUtilities.removeAllMessages(wsdlImplementativo);
  1154.         this.wsdlUtilities.removeAllPortTypes(wsdlImplementativo);
  1155.        
  1156.         if (portTypes == null) {
  1157.             //Importo il logico
  1158.             wsdlImplementativo.removeAllImports();
  1159.             wsdlImplementativo.addImport(logico);
  1160.             removeExtensibilityElements(wsdlImplementativo.getTypes());
  1161.             return;
  1162.         }
  1163.         Map<?,?> m = wsdlImplementativo.getBindings();
  1164.         Iterator<?> it = m.values().iterator();
  1165.         //creo il vettore dei binding corretti.
  1166.         List<Binding> bnd = new ArrayList<Binding>();
  1167.         while (it.hasNext()){
  1168.             Binding now = wsdlImplementativo.getBinding(((Binding)it.next()).getQName());
  1169.             String refPTName = now.getPortType().getQName().getLocalPart();
  1170.             boolean found = false;
  1171.             int i=0;
  1172.             for (int j=portTypes.length; i<j; i++){
  1173.                 if (refPTName.equals(portTypes[i]))
  1174.                 {
  1175.                     found = true;
  1176.                     break;
  1177.                 }
  1178.             }
  1179.             if (found){
  1180.                 List<?> ops = now.getBindingOperations();
  1181.                 String[] myops = operations[i].split(",");
  1182.                 List<String> toDel = new ArrayList<>();
  1183.                 for (int h=0, k=ops.size(); h<k; h++){
  1184.                     String curName = ((BindingOperation)ops.get(h)).getName();
  1185.                     boolean rem = true;
  1186.                     for (int mm=0, n=myops.length; mm<n; mm++){
  1187.                         if (myops[mm].equals(curName))
  1188.                         {
  1189.                             rem = false;
  1190.                             break;
  1191.                         }
  1192.                     }
  1193.                     if (rem)
  1194.                         toDel.add(curName);
  1195.                     //now.removeBindingOperation(myops[h], null, null);
  1196.                 }
  1197.                 for (int x=0, y=toDel.size(); x<y; x++)
  1198.                     now.removeBindingOperation(toDel.get(x), null, null);
  1199.             }

  1200.             bnd.add(now);

  1201.         }

  1202.         /** PULIZIA BINDINGS */
  1203.         m = wsdlImplementativo.getAllBindings();
  1204.         it = m.values().iterator();
  1205.         while (it.hasNext()){
  1206.             Binding now = (Binding) it.next();
  1207.             String cuBinName = now.getPortType().getQName().getLocalPart();
  1208.             boolean delete = true;
  1209.             for(int i=0; i<portTypes.length;i++){
  1210.                 String check = portTypes[i];
  1211.                 //System.out.println("CONFRONTO ["+check+"] con ["+cuBinName+"]");
  1212.                 if (check.equals(cuBinName))
  1213.                 {
  1214.                     delete = false;
  1215.                     break;
  1216.                 }
  1217.             }
  1218.             if (delete){
  1219.                 wsdlImplementativo.removeBinding(now.getQName());
  1220.             }
  1221.         }

  1222.         /** PULIZIA SERVICES */
  1223.         m = wsdlImplementativo.getAllServices();
  1224.         it = m.values().iterator();
  1225.         while (it.hasNext()){
  1226.             Service now = (Service) it.next();
  1227.             Map<?,?> pts = now.getPorts();
  1228.             Iterator<?> ports = pts.values().iterator();
  1229.             boolean delete = true;
  1230.             while (ports.hasNext()){
  1231.                 //if (debug) System.out.println("Iterazione "+iter);
  1232.                 Port cuPor = (Port) ports.next();
  1233.                 String cuBinName = cuPor.getBinding().getPortType().getQName().getLocalPart();
  1234.                 for(int i=0; i<portTypes.length;i++){
  1235.                     String check = portTypes[i];
  1236.                     //System.out.println("CONFRONTO ["+check+"] con ["+cuBinName+"]");
  1237.                     if (check.equals(cuBinName))
  1238.                     {
  1239.                         delete = false;
  1240.                         break;
  1241.                     }
  1242.                 }
  1243.             }
  1244.             if (delete){
  1245.                 wsdlImplementativo.removeService(now.getQName());
  1246.             }
  1247.         }

  1248.         //Importo il logico
  1249.         wsdlImplementativo.removeAllImports();
  1250.         wsdlImplementativo.addImport(logico);
  1251.         removeExtensibilityElements(wsdlImplementativo.getTypes());
  1252.        
  1253.     }
  1254.    
  1255.     private void writeImplementativoErogatoreTo(File dir,boolean prettyPrint) throws WSDLException, IOException, org.openspcoop2.utils.wsdl.WSDLException{
  1256.         this.wsdlUtilities.writeWsdlTo(this.wsdlImplementativoErogatore,
  1257.                 dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_IMPLEMENTATIVI + File.separator + SplitWSDL.IMPLEMENTATIVO_EROGATORE_FILENAME,
  1258.                 prettyPrint);
  1259.     }
  1260.    
  1261.     private void writeImplementativoFruitoreTo(File dir,boolean prettyPrint) throws WSDLException, IOException, org.openspcoop2.utils.wsdl.WSDLException{
  1262.         this.wsdlUtilities.writeWsdlTo(this.wsdlImplementativoFruitore,
  1263.                 dir.getAbsolutePath() + File.separator + SplitWSDL.FOLDER_IMPLEMENTATIVI + File.separator + SplitWSDL.IMPLEMENTATIVO_FRUITORE_FILENAME,
  1264.                 prettyPrint);
  1265.     }
  1266.    
  1267.    
  1268.    
  1269.    
  1270.    
  1271.    
  1272.    
  1273.    
  1274.    
  1275.    
  1276.    
  1277.    
  1278.    
  1279.    
  1280.     /* ------------------- UTILITIES GENERALI ----------------------------- */
  1281.    
  1282.     private void removeExtensibilityElements(WSDLElement ele){
  1283.         List<?> ext = ele.getExtensibilityElements();
  1284.         while (ext.size()>0){
  1285.             ele.removeExtensibilityElement((ExtensibilityElement) ext.get(0));
  1286.             ext = ele.getExtensibilityElements();
  1287.         }
  1288.     }
  1289.    
  1290.     private String[] merge(String[] a, String[] b){
  1291.         if(a==null) return b;
  1292.         if(b==null) return a;
  1293.         String[] c = new String[a.length + b.length];
  1294.         int i = 0;
  1295.         for(int j=0; j<a.length;j++){
  1296.             c[i] = a[j];
  1297.             i++;
  1298.         }
  1299.         for(int j=0; j<b.length;j++){
  1300.             c[i] = b[j];
  1301.             i++;
  1302.         }
  1303.         return c;
  1304.     }
  1305.    

  1306. }