View Javadoc

1   package it.imolinfo.jbi4corba.utils;
2   
3   import it.imolinfo.jbi4corba.utils.plugin.wsdl.Jbi4CorbaPartnerLink;
4   import it.imolinfo.jbi4corba.utils.plugin.wsdl.Jbi4CorbaPartnerLinkExtension;
5   import it.imolinfo.jbi4corba.utils.plugin.wsdl.Role;
6   import it.imolinfo.jbi4corba.schema.DefinitionAndSchema;
7   import it.imolinfo.jbi4corba.webservice.generator.WSDLDescriptor;
8   import it.imolinfo.jbi4corba.webservice.generator.WSDLGenerator;
9   import java.io.File;
10  import java.io.IOException;
11  import java.util.ArrayList;
12  import java.util.Iterator;
13  import java.util.List;
14  import java.util.Map;
15  import javax.wsdl.Definition;
16  import javax.wsdl.WSDLException;
17  import javax.xml.namespace.QName;
18  import com.ibm.wsdl.util.xml.DOMUtils;
19  import it.imolinfo.jbi4corba.jbi.wsdl.Jbi4CorbaExtension;
20  import java.io.FileInputStream;
21  import java.io.FileOutputStream;
22  import java.io.FileWriter;
23  import java.io.PrintStream;
24  import java.util.Date;
25  import java.util.Properties;
26  import java.util.Vector;
27  import javax.wsdl.extensions.ExtensionRegistry;
28  import javax.wsdl.factory.WSDLFactory;
29  import javax.wsdl.xml.WSDLWriter;
30  
31  /**
32   * MainCommandLine - class with the main method
33   * @author Federico Pavoncelli
34   */
35  public class IDL2WSDLTool {
36      
37      
38          /**
39       * The Column Number that contain the number of Interface Selected for Creation
40       */
41      private final static int SELECTED_FOR_CREATION=0;
42      
43           /**
44       * The Column that contain the Endpoint Name
45       */
46      private final static int ENDPOINT_NAME=1;
47      
48       /**
49       * The Column that contain the descriptor info
50       */
51      private final static int DESC_INFO=3; 
52      
53      private final static String LOG_FILE_NAME="IDL2WSDLTool.log";
54      
55      private final static String LINE_SEPARATOR="-----------------------------------------------------------";
56   
57      private static PrintStream pos = null;
58      
59      public static void main(String[] args) {
60          
61          
62          //args=new String[2];
63          // testAny
64          // AlarmIRPSystem
65          //args[0]="AlarmIRPSystem.idl";
66          //args[0]="C:/Users/fedeb/AppData/Local/Temp/jbi4corba.properties";
67          //args[1]="C:/Users/fedeb/AppData/Local/Temp/jbi4corba.properties";
68  
69          if ((args==null)||(args.length!=2)) {
70              logConsole("Two arguments are required: idl_file_name property_file_name");
71          }
72          
73          String fn =null;
74          
75          File work = new File(args[0]);
76          try {
77              fn = work.getCanonicalPath();
78          } catch (IOException e) {
79              logConsole("File idl not found");
80          }
81          /*
82          File logDir = new File (fn);
83          String logFile;
84          try {
85              logFile = logDir.getParentFile().getCanonicalPath();
86              FileOutputStream fos = new FileOutputStream(logFile+File.separator+LOG_FILE_NAME,false);
87              pos = new PrintStream(fos);
88              pos.println("WSDL generation started at "+new Date());
89          }  catch (IOException ex) {
90              ex.printStackTrace();
91              System.exit(-1);
92          }  
93         */
94  
95          final String baseTempPath = System.getProperty("java.io.tmpdir");
96          try {
97              String fileNameAbsolute = new File(baseTempPath).getCanonicalPath()+File.separator+LOG_FILE_NAME;
98              FileOutputStream fos = new FileOutputStream(fileNameAbsolute,false);
99              pos = new PrintStream(fos);
100             pos.println("WSDL generation started at "+new Date());
101             pos.println(LINE_SEPARATOR);
102             pos.println("Arg0 "+args[0] );
103             pos.println("Arg1 "+args[1] );
104             pos.println(LINE_SEPARATOR);
105         }  catch (IOException ex) {
106             ex.printStackTrace();
107             System.exit(-1);
108         } 
109         
110         
111         Properties properties = new Properties();
112         try {
113             properties.load(new FileInputStream(args[1]));
114         } catch (IOException e) {
115             logConsole("Property file not found",e);
116         }
117            
118         String num = properties.getProperty("InterfaceCount");
119         
120         if (num==null) {
121               logConsole("InterfaceCount property not found");
122         }
123         int iNum =0;
124         try {
125             iNum = Integer.parseInt(num);
126             if (iNum<1) throw new NumberFormatException();
127         } catch (NumberFormatException nfe) {
128             logConsole("Property iNum must be a number greater than 0");
129         }
130 
131         Object[][] descInfo = new Object[iNum][4];
132 
133         for (int i = 0; i < iNum; i++) {
134             String PRE = "Interface" + i + ".";
135             
136             String IDLInterfaceName = properties.getProperty(PRE + "IDLInterfaceName");
137             String fileName = properties.getProperty(PRE + "FileName");
138             String address = properties.getProperty(PRE + "Address");
139             String localizationType = properties.getProperty(PRE + "LocalizationType");
140             boolean persistent=Boolean.valueOf(properties.getProperty(PRE + "Persistent", "false"));
141 
142             if (IDLInterfaceName==null) {
143                 logConsole("IDLInterfaceName property not found");
144             } else if (fileName==null) {
145                 logConsole("FileName property not found");
146             } else if (address==null) {
147                 logConsole("Address property not found");
148             } else if (localizationType==null) {
149                 logConsole("LocalizationType property not found");
150             }
151          
152             descInfo[i][0] = Boolean.TRUE;
153             descInfo[i][1] = IDLInterfaceName;
154             descInfo[i][2] = fileName;
155 
156             DescInfo di = new DescInfo();
157             di.setAddress(address);
158             di.setLocalizationType(localizationType);
159             di.setPersistent(persistent);
160             //int val = Integer.parseInt(properties.getProperty(PRE + "ORBType"));
161             //di.setORBType(val);
162 
163             Vector prop = new Vector();
164             
165             String ORBPropertiesCount = properties.getProperty(PRE + "ORBPropertiesCount");
166             int nProp = 0;
167             if (ORBPropertiesCount!=null) {
168                 try {
169                     nProp = Integer.parseInt(ORBPropertiesCount);
170                     if (nProp<1) throw new NumberFormatException();
171              
172                 } catch (NumberFormatException nfe) {
173                     logConsole("ORBPropertiesCount property must be a number greater than 0");
174                 }
175 
176                 for (int z = 0; z < nProp; z++) {
177                     Object[] arr = new Object[2];
178 
179                     String name = properties.getProperty(PRE + "ORBPropertyName" + z);
180                     String value = properties.getProperty(PRE + "ORBPropertyValue" + z);
181                     
182                     if (name==null) {
183                       logConsole("ORBPropertyName property not found");
184                     }
185                     if (value==null) {
186                       logConsole("ORBPropertyValue property not found");
187                     }
188                     arr[0] = name;
189                     arr[1] = value;
190                     prop.add(arr);
191                 }
192 
193                 di.setProperties(prop);
194                 descInfo[i][3] = di;
195             }
196 
197         }
198         // start generating WSDL
199 
200         File idl = new File(fn);
201         List<IdlFileDataHolder> idldata = loadInterfaces(idl);
202         ArrayList<WSDLDescriptor> descList = createWSDLDescList(descInfo, idldata);
203 
204         WSDLGenerator generator = WSDLGenerator.getWSDLGenerator();
205         try {
206 
207             //****Component Side*****
208             List<Definition> defList = null;
209             defList = generator.generateWSDLListfromIDL(idl, descList);
210 
211 
212 
213             DefinitionAndSchema defSchema = generator.createRemoveXSD(defList);
214             int index = 0;
215 
216             //WSDL Creation For Each Definition
217 
218             for (Definition def : defSchema.getDefinitions()) {
219 
220 
221                 String nameFile = def.getQName().getLocalPart();
222                 String wsdlFileName = idl.getParent() + File.separatorChar + nameFile + ".wsdl";
223 
224                 File wsdl = new File(wsdlFileName);
225 
226                 //Change File Name for correct generation
227                 int i = 1;
228                 while (wsdl.exists()) {
229 
230                     wsdlFileName = idl.getParent() + File.separatorChar + nameFile + "_" + i + ".wsdl";
231                     wsdl = new File(wsdlFileName);
232                     i++;
233                 }
234 
235                 // adding the partner link to the generated file
236                 if (def != null) {
237                     def = addPartnerLinkToWSDL(def, def.getQName().getLocalPart());
238                     //def
239                     createFileFromWSDL(def, wsdl);
240                 }
241 
242             }
243 
244             //System.err.println("efSchema.isContainsW3c():" + defSchema.isContainsW3c());
245             //System.err.println("idl.getParent():" + idl.getParent());
246 
247 
248 
249             //Write XSD
250             if (defSchema.isContainsW3c()) {
251                 it.imolinfo.jbi4corba.schema.SchemaUtil.createW3CSchema(idl.getParent());
252             }
253 
254             //System.err.println("defSchema.getSchemas().size();:" + defSchema.getSchemas().size());
255             //System.out.println("WSDL successfully generated at "+new Date());
256             
257         
258             it.imolinfo.jbi4corba.schema.SchemaUtil.createXSD(defSchema.getSchemas(), idl.getParent(), "TypeDef");
259 
260 
261         //} finally {
262         //    Thread.currentThread().setContextClassLoader(oldCl);
263         //}
264 
265         } catch (Exception ex) {
266             logConsole("Internal Error :  "+ex.getMessage(), ex);
267 
268         } 
269         pos.println("WSDL successfully generated at "+new Date());
270         pos.close();
271         System.exit(0);
272     }
273 
274 
275     /**
276    * Adds the deafult partner-link to the wsdl
277    */
278   private static Definition addPartnerLinkToWSDL(Definition definition, String corbaServiceName) throws WSDLException, IOException {
279 
280 
281     Jbi4CorbaPartnerLink ptnlnk = new Jbi4CorbaPartnerLink();
282 
283     // check if name space is present
284     String prefix = definition.getPrefix(Jbi4CorbaPartnerLinkExtension.NS_PTNLNK);
285     if (prefix == null) {
286       // add the namespace
287       definition.addNamespace(Jbi4CorbaPartnerLinkExtension.NS_PREFIX, Jbi4CorbaPartnerLinkExtension.NS_PTNLNK);
288       prefix = Jbi4CorbaPartnerLinkExtension.NS_PREFIX;
289     }
290 
291     // FEDE TODO
292     //log.fine("The used prefix: " + prefix);
293 
294     // use the existing prefix
295     ptnlnk.setPrefix(prefix);
296 
297     // set the partner link name as the corba service name
298     ptnlnk.setName(corbaServiceName);
299 
300     // set the required to true
301     ptnlnk.setRequired(true);
302 
303     // set the element type
304     ptnlnk.setElementType(Jbi4CorbaPartnerLinkExtension.Q_ELEMENT_PTNLNK);
305 
306     // isolating the portType
307     Map portTypes = definition.getAllPortTypes();
308     Role role = null;
309     if (portTypes.size() > 0) {
310       Iterator iterKeys = portTypes.keySet().iterator();
311       Iterator iterValues = portTypes.values().iterator();
312       do {
313         QName key = (QName) iterKeys.next();
314         javax.wsdl.PortType value = (javax.wsdl.PortType) iterValues.next();
315 
316         // find the target name space
317         String tns = value.getQName().getNamespaceURI();
318         if (tns == null) {
319           // Impossible: the tns must be defined
320           // FEDE TODO
321           //String msg = NbBundle.getMessage(CreateWSDLAction.class, "MSG_TargetNamespaceNotFound");
322           //NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE);
323 
324 
325           //DialogDisplayer.getDefault().notify(nd);
326           logConsole("Errore: MSG_TargetNamespaceNotFound");
327           return null;
328         }
329         role = new Role(corbaServiceName + Jbi4CorbaPartnerLinkExtension.ROLE_NAME_SUFFIX, DOMUtils.getPrefix(tns, definition) + ":" + value.getQName().getLocalPart());
330         ptnlnk.addRole(role);
331         portTypes.remove(key);
332       } while (!portTypes.isEmpty());
333     }
334 
335     // adds the extension
336     definition.addExtensibilityElement(ptnlnk);
337 
338     return definition;
339   }
340 
341 
342    /**
343    * Creates the wsdl file from the <code>Definition</code>.
344    */
345   private static boolean createFileFromWSDL(Definition definition, File wsdlFile) throws WSDLException, IOException {
346     boolean result = false;
347 
348     FileWriter fw = null;
349 
350     try {
351       WSDLFactory factory = WSDLFactory.newInstance();
352       // creating the registry for the WSDL4J Extension
353       ExtensionRegistry registry = factory.newPopulatedExtensionRegistry();
354       Jbi4CorbaPartnerLinkExtension.register(registry);
355       Jbi4CorbaExtension.register(registry);
356       it.imolinfo.jbi4corba.schema.SchemaUtil.registerSchema(registry);
357       definition.setExtensionRegistry(registry);
358 
359       // creating the writer
360       WSDLWriter writer = factory.newWSDLWriter();
361 
362       // creating the new File
363       fw = new FileWriter(wsdlFile);
364 
365       // write the file
366       writer.writeWSDL(definition, fw);
367 
368       result = true;
369     } finally {
370       if (fw != null) {
371         fw.close();
372       }
373     }
374 
375     return result;
376   }
377     /**
378     * Prepare the  WSDLDescriptors for the wsdl creation
379     */
380     private static ArrayList<WSDLDescriptor> createWSDLDescList(Object[][] descInfos,List<IdlFileDataHolder> idlHolder){
381         
382         
383         ArrayList<WSDLDescriptor> descList=new ArrayList<WSDLDescriptor>();
384         String namespace="";
385        
386         //Create the WSDL DESCRIPTOR
387         for (int i=0;i<descInfos.length;i++){
388             boolean  selected =(Boolean)descInfos[i][SELECTED_FOR_CREATION];
389             DescInfo descInfo=(DescInfo)descInfos[i][DESC_INFO];
390             String name=(String)descInfos[i][ENDPOINT_NAME];
391             //If the interface is selected for the creation , we have to fill the WSDLDescriptor
392             if(selected){
393                 for(int k=0;k<idlHolder.size();k++){
394                     if(idlHolder.get(k).getInterfaceName().equals(name)){
395                         namespace=idlHolder.get(k).getInterfaceNameSpace();
396                     }
397                 }
398                 
399                 String locType="";
400                 String corbaSVCName="";
401                 if(descInfo.isStateless()){
402                     locType=descInfo.getLocalizationType();    
403                     corbaSVCName=descInfo.getAddress();
404                 }
405               
406                 WSDLDescriptor desc =new WSDLDescriptor(corbaSVCName,locType,namespace,name);      
407                 desc.setOrbProperties(descInfo.getProperties());
408                 desc.setPersistentConsumer(descInfo.isPersistent());
409                 descList.add(desc);
410             }
411                 
412         }
413        
414         return descList;
415     }
416     
417     /**
418      * This Method Load the Interfaces and namespaces from idl and store it 
419      * in a IdlDataHolder 
420      **/
421      private static List<IdlFileDataHolder> loadInterfaces(File idl){
422         List<IdlFileDataHolder> idlData=null;
423         idlData=new ArrayList<IdlFileDataHolder>(); 
424         WSDLGenerator generator = WSDLGenerator.getWSDLGenerator();
425         try {
426             idlData = generator.getIdlFileData(idl);
427         } catch (Exception ex) {
428             logConsole(ex.getMessage(),ex );
429         }
430   
431        return idlData;
432         
433     }
434      
435      private static void logConsole(String message, Exception e) {
436         System.err.println(message);
437         pos.println(message);
438         if (e!=null) {
439             pos.println("\nStackTrace :");
440             pos.println(e);
441         }
442         pos.println(LINE_SEPARATOR);
443         pos.close();
444         System.exit(-1);
445      }
446      private static void logConsole(String message) {
447          logConsole(message,null);
448      }
449      
450      
451      
452 
453 }
454