View Javadoc

1    /****************************************************************************
2    * Copyright (c) 2005, 2006, 2007, 2008, 2009 Imola Informatica.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the LGPL License v2.1
5    * which accompanies this distribution, and is available at
6    * http://www.gnu.org/licenses/lgpl.html
7    ****************************************************************************/
8   package it.imolinfo.jbi4corba.webservice.generator;
9   
10  import it.imolinfo.jbi4corba.Logger;
11  import it.imolinfo.jbi4corba.LoggerFactory;
12  import it.imolinfo.jbi4corba.exception.ClassGenerationException;
13  import it.imolinfo.jbi4corba.exception.Jbi4CorbaException;
14  import it.imolinfo.jbi4corba.jbi.JbiServiceDescriptor;
15  import it.imolinfo.jbi4corba.jbi.Messages;
16  import it.imolinfo.jbi4corba.jbi.cxf.CXFUtils;
17  import it.imolinfo.jbi4corba.utils.HelperFileUtil;
18  import it.imolinfo.jbi4corba.webservice.generator.bcm.AddExceptionSuperclass;
19  import it.imolinfo.jbi4corba.webservice.generator.bcm.RemoteEnhancerAdapter;
20  import it.imolinfo.jbi4corba.webservice.generator.bcm.UIDAdapter;
21  import it.imolinfo.jbi4corba.webservice.generator.bcm.ValueTypeAdapter;
22  import it.imolinfo.jbi4corba.webservice.generator.bcm.WsdlToCorbaAdapter;
23  
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileNotFoundException;
27  import java.io.FileOutputStream;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.PrintWriter;
31  import java.io.StringWriter;
32  import java.net.MalformedURLException;
33  import java.net.URL;
34  import java.net.URLClassLoader;
35  import java.util.ArrayList;
36  import java.util.Arrays;
37  import java.util.Iterator;
38  import java.util.List;
39  import java.util.Map;
40  import java.util.Set;
41  
42  import javax.wsdl.Definition;
43  import javax.wsdl.factory.WSDLFactory;
44  import javax.wsdl.xml.WSDLReader;
45  import javax.xml.namespace.QName;
46  
47  import org.apache.commons.vfs.FileObject;
48  import org.apache.commons.vfs.FileSystemException;
49  import org.apache.commons.vfs.FileSystemManager;
50  import org.apache.commons.vfs.VFS;
51  import org.apache.cxf.service.model.OperationInfo;
52  import org.apache.cxf.service.model.ServiceInfo;
53  import org.apache.cxf.tools.common.ToolContext;
54  import org.apache.cxf.tools.wsdlto.WSDLToJava;
55  import org.apache.cxf.wsdl11.WSDLServiceBuilder;
56  import org.objectweb.asm.ClassAdapter;
57  import org.objectweb.asm.ClassReader;
58  import org.objectweb.asm.ClassVisitor;
59  import org.objectweb.asm.ClassWriter;
60  import org.objectweb.asm.util.CheckClassAdapter;
61  import org.objectweb.asm.util.TraceClassVisitor;
62  
63  import com.ibm.wsdl.Constants;
64  import com.ibm.wsdl.factory.WSDLFactoryImpl;
65  
66  
67  /**
68   * This class generates (at deploy time) the code used by the jbi4corba
69   * in 'consumer' mode (at run time).
70   *
71   */
72  public class ConsumerServiceClassesGenerator {
73  
74    /**
75     * Logger.
76     */
77    private static final Logger LOG
78      = LoggerFactory.getLogger(ConsumerServiceClassesGenerator.class);
79    private static final Messages MESSAGES = 
80    	Messages.getMessages(ConsumerServiceClassesGenerator.class);
81  
82  
83    /**
84     * Default constructor.
85     */
86    public ConsumerServiceClassesGenerator() {
87      // NOP
88    }
89  
90    /**
91     * This method is used to generate all the consumer code starting from the
92     * WSDL of the Endpoint to consume.
93     *
94     * Steps:
95     * 1) code generation: wsdl to java
96     * 2) compile the new source
97     * 3) bytecode manipultion: the classes must be modified to use rmic
98     * 4) compile with rmic to generate the corba classes
99     * 5) add the getter, setter and serialVersionUID to the class
100    * 6) save all the objects in the ServerCorbaClassesHolder
101    *
102    *
103    * @param wsdlStringUrl   Where the WSDL is located.
104    * @param workdir         Where the method can generate the code.
105    * @param jars            The jar needed at compile time and run time.
106    *
107    * @param All the references to the object generated.
108    *
109    * @throws  ClassGenerationException    When the code cannot be generated.
110    *
111    */
112   public ServerCorbaClassesHolder generateConsumerServiceClasses(
113           String wsdlStringUrl,
114           String workdir,
115           String libDirName,
116           JbiServiceDescriptor jbiServiceDescriptor) throws ClassGenerationException {
117 
118       LOG.debug(">>>>> generateConsumerServiceClasses - begin");
119 
120       // ===================================
121       //       find jar list used to compile
122       // ===================================
123       List<String> jars = Util.prepareClassPath(libDirName);
124 
125       //ServerCorbaClassesHolder s
126       //    = generateConsumerServiceClasses(wsdlStringUrl, workdir, jars);
127 
128       ServerCorbaClassesHolder s
129         = generateConsumerServiceClassesDirect(wsdlStringUrl, workdir, jars, jbiServiceDescriptor);
130 
131       LOG.debug("<<<<< generateConsumerServiceClasses - end");
132       return s;
133   }
134 
135 //    /**
136 //     * This method implements the follow algorithm:
137 //     *
138 //     *  1) retrieving the WSDL.
139 //     *  2) creating a (unique) directory (called wsdlDir).
140 //     *  3) copy the WSDL in the wsdlDir.
141 //     *  4) copy the ir.idl and orb.idl in the wsdlDir.
142 //     *  5) creating the wsdlDir/src and wsdlDir/classes directories.
143 //     *  6) creating the list of the jars distribuited with the component.
144 //     *  7) execute a 'wsdl to java' operation using CXF.
145 //     *  8) compiling the classes generated.
146 //     *  9) retrieving the 'interface class' (The one with the suffix ).
147 //     * 10) adding RMIRemote to the PortType class
148 //     * 11) compiling all the source code using RMIC to generate the IDLs
149 //     * 12) moving the IDLs in the wsdlDir
150 //     * 13) creating the servant classes (and recompiling)
151 //     * 14) retrieving the classes needed at 'run time' using the class loader.
152 //     *  ...
153 //     *
154 //     * @param    wsdlStringUrl    Where the WSDL is located
155 //     * @param    workdir          The working directory
156 //     * @param    jars             The list of the libraries
157 //     *
158 //     * @return    The classes generated
159 //     *
160 //     * @throws    ClassGenerationException  The class generation exception
161 //     */
162 //    public ServerCorbaClassesHolder generateConsumerServiceClasses(
163 //        String wsdlStringUrl,
164 //        String workdir,
165 //        List<String> jars) throws ClassGenerationException {
166 //
167 //        LOG.debug(">>>>> generateConsumerServiceClasses - begin");
168 //
169 //        LOG.debug("generateConsumerServiceClasses"
170 //                + ". wsdlStringUrl=" + wsdlStringUrl
171 //                + "; workdir="       + workdir
172 //                + "; jars="          + jars);
173 //
174 //        // ========================================
175 //        // copying wsdl from url to local directory
176 //        // ========================================
177 //
178 //        File wsdlDirFile = copyWsdlTo(workdir, wsdlStringUrl);
179 //
180 //        String wsdlDirName = null;
181 //        try {
182 //            wsdlDirName = wsdlDirFile.getCanonicalPath();
183 //        } catch (IOException ioe) {
184 //            LOG.error("CRB000500_Error_accessing_the_WSDL_directory", ioe);
185 //            throw new ClassGenerationException(
186 //                    "CRB000500_Error_accessing_the_WSDL_directory", ioe);
187 //        }
188 //
189 //        // ==========================
190 //        //     add orb.idl and ir.idl
191 //        // ==========================
192 //        copyOrbIrIdl(wsdlDirName);
193 //
194 //        // ==================================================
195 //        //                preparing directory (src + classes)
196 //        // ==================================================
197 //        String sourceDirName = mkdir(wsdlDirFile, "src");
198 //        final String classesDirName = mkdir(wsdlDirFile, "classes");
199 //
200 //        // =======================================
201 //        // generating source files  (WSDL to JAVA)
202 //        // =======================================
203 //        WsdlInformation wsdlInformation
204 //          = wsdlToJava(wsdlDirName, sourceDirName);
205 //
206 //        List<QName> portTypeList = wsdlInformation.getPortTypeList();
207 //
208 //        // ======================
209 //        // compiling java classes
210 //        // ======================
211 //        List<String> sources = javac(sourceDirName, classesDirName, jars);
212 //
213 //        // ===============================
214 //        // finding <Service>PortType.class
215 //        //================================
216 //        //String portTypeClassName = findingPortTypeClassName(classesDirName);
217 //        String portTypeClassName
218 //                = findingPortTypeClassName(portTypeList, classesDirName);
219 //        
220 //        // ========================================
221 //        // ByteCode Manipulation:
222 //        // add the correct exceptions to the throws clause
223 //        // of the remote interface (the generated interface
224 //        // throws a FaultInfoException).
225 //        // Decomment when working on issue CRB-118 
226 //        //=========================================        
227 //        // tweakRemoteInterfaceGeneratedFromWSDL(portTypeClassName,
228 //        //                                       classesDirName); 
229 //
230 //        // ========================================
231 //        // ByteCode Manipulation: add Remote
232 //        //=========================================
233 //        String remoteClassName = tweakInterfaceClasses(portTypeClassName,
234 //                                                       classesDirName);
235 //
236 //        // ========================================
237 //        // ByteCode Manipulation: valuetype
238 //        // ========================================
239 //        List<String> modifiedClassNames
240 //          = tweakValueType(remoteClassName, classesDirName);
241 //
242 //        Map<String, AnnotationsMaps> annota = tweakAnnotationCollector(
243 //          modifiedClassNames, classesDirName);
244 //
245 //        for (String currentClass : annota.keySet()) {
246 //            AnnotationsMaps tracer = annota.get(currentClass);
247 //
248 //            LOG.debug("TRACER. currentClass=" + currentClass
249 //              + "; tracer=" + tracer);
250 //        }
251 //
252 //        // compile tweaked class with rmic
253 //        Util.compileRemoteClassesNoValueMethodsON(classesDirName,
254 //                                                  remoteClassName,
255 //                                                  jars);
256 //        String idlFilename
257 //            = classesDirName
258 //            + File.separator
259 //            + remoteClassName.replace('.', File.separatorChar)
260 //            + ".idl";
261 //
262 //        String destIdlFileName
263 //            = wsdlDirName
264 //            + File.separator
265 //            + remoteClassName.substring(remoteClassName.lastIndexOf('.') + 1)
266 //            + ".idl";
267 //
268 //        // =========================
269 //        //        move all idl files
270 //        // =========================
271 //        copyIDLs(classesDirName, wsdlDirName, remoteClassName);
272 //
273 //        // =================================
274 //        //       compile new idl with poaTie
275 //        // =================================
276 //        idl2javaTieModel(sourceDirName, idlFilename, wsdlDirName, destIdlFileName);
277 //
278 //        // =================================
279 //        //      VALUETYPE IDL IMPLEMENTATION
280 //        // =================================
281 //        List<String> vtList = Util.valueTypesImpl(sourceDirName, true);
282 //        LOG.debug("end creating java sources implementation for value types.");
283 //
284 //        // =================================
285 //        // Code Generation: new factories
286 //        // XxxDefaultFactoryJbi4corba
287 //        // =================================
288 //        Util.generateValueTypeFactoryJbi4corba(vtList, sourceDirName);
289 //
290 //        // =========================
291 //        // re-compiling java classes
292 //        // =========================
293 //        LOG.debug("re-compiling java classes - begin");
294 //        try {
295 //            int last = remoteClassName.lastIndexOf(".");
296 //            String objectFactoryPackage = remoteClassName.substring(0, last);
297 //
298 //            List<String> no = new ArrayList<String>();
299 //            no.add(objectFactoryPackage + ".ObjectFactory");
300 //
301 //            // the list of java file that will be not compile again
302 //            List<String> excludes
303 //                = exctractJavaListJavaName(no, sourceDirName);
304 //
305 //            sources = Util.findJavaSources(sourceDirName, excludes);
306 //
307 //        } catch (Jbi4CorbaException e) {
308 //            Object[] args = new Object[] { sourceDirName, e.getMessage() };
309 //
310 //            LOG.error("CRB000501_Error_generating_sources_list", args, e);
311 //            throw new ClassGenerationException(
312 //                    "CRB000501_Error_generating_sources_list", args, e);
313 //        }
314 //
315 //        LOG.debug("re-compiling java classes - pre Util.compileJavaClasses");
316 //
317 //        List<String> extra = new ArrayList<String>();
318 //        extra.add(classesDirName);
319 //
320 //        Util.compileJavaClasses(sourceDirName,
321 //                                classesDirName,
322 //                                sources,
323 //                                jars,
324 //                                extra);
325 //
326 //        LOG.debug("re-compiling java classes - end");
327 //
328 //        // =================================
329 //        //  ADAPTING AUTOGENERATED VALUETYPE
330 //        // =================================
331 //        tweakWsdlToCorba(vtList, classesDirName);
332 //        LOG.debug("end creating java sources implementation for value types.");
333 //
334 //        tweakAnnotationWriter(classesDirName, annota);
335 //
336 //        // =======================
337 //        //instantiate class loader
338 //        // =======================
339 //        URLClassLoader urlClassLoader = getURLClassLoader(classesDirName);
340 //
341 //        LOG.debug("instantiate class loader ... done");
342 //
343 //        //now we need the following classes
344 //        //<remoteClass>CorbaInterfaceOperations
345 //        //<remoteClass>CorbaInterfacePOATie
346 //        //<remoteClass>ServicePortType
347 //        //<remoteClass>CorbaInterfaceHelper
348 //
349 //        String classRoot = remoteClassName.substring(
350 //                0, remoteClassName.indexOf("CorbaInterface"));
351 //
352 //        LOG.debug("FROM remoteClassName=" + remoteClassName
353 //                + "; TO classRoot=" + classRoot);
354 //
355 //        String operations = classRoot + "CorbaInterfaceOperations";
356 //        String poaTie     = classRoot + "CorbaInterfacePOATie";
357 //        //String portType   = classRoot + "ServicePortType";
358 //        String portType   = portTypeClassName;
359 //        String helper     = classRoot + "CorbaInterfaceHelper";
360 //
361 //        // Takes the service of the first port type
362 //        String serviceName
363 //          = extractServiceNameFromPortType(wsdlDirName, portTypeList.get(0));
364 //        String portTypePackage
365 //          = portTypeClassName.substring(0, portTypeClassName.lastIndexOf('.'));
366 //        String serviceImpl = portTypePackage + "." + serviceName + "Impl";
367 //
368 //        LOG.debug("classRoot="     + classRoot
369 //                + "; operations="  + operations
370 //                + "; poaTie="      + poaTie
371 //                + "; portType="    + portType
372 //                + "; helper="      + helper
373 //                + "; serviceImpl=" + serviceImpl);
374 //
375 //        ServerCorbaClassesHolder serverCorbaClassesHolder
376 //            = new ServerCorbaClassesHolder();
377 //
378 //        setCorbaOperations(serverCorbaClassesHolder,
379 //                           urlClassLoader,
380 //                           operations);
381 //
382 //        setCorbaPOATie(serverCorbaClassesHolder, urlClassLoader, poaTie);
383 //
384 //        setWebServiceInterface(serverCorbaClassesHolder,
385 //                               urlClassLoader,
386 //                               portType);
387 //        setCorbaHelper(serverCorbaClassesHolder, urlClassLoader, helper);
388 //
389 //        serverCorbaClassesHolder.setUrlClassLoader(urlClassLoader);
390 //
391 //        setWebServiceImpl(serverCorbaClassesHolder,
392 //                          urlClassLoader,
393 //                          serviceImpl);
394 //
395 //        Map<String, Object> map = Util.valueTypeMapHandlerWithJbi4corbaFactory(
396 //          vtList, classesDirName, urlClassLoader);
397 //
398 //        serverCorbaClassesHolder.setValueTypeIdAndInstance(map);
399 //        serverCorbaClassesHolder.setWsdlInformation(wsdlInformation);
400 //
401 //        LOG.debug("<<<<< generateConsumerServiceClasses - end");
402 //        return serverCorbaClassesHolder;
403 //    }
404 
405   /**
406    * This Method copy all the xsd in the work dir 
407    * @param  srcDir the XSD source directory URL
408    * @param  wsdlDirFile Destination folder
409    * @throws ClassGenerationException 
410    **/
411   private void copyXSDFile(String srcDir,File wsdlDirFile) throws ClassGenerationException{
412        
413             List<File> xdsList = Util.findFilesFromSourceDirectory(srcDir, ".xsd");
414          
415             for (File xsd : xdsList) {
416 
417                 LOG.debug("Copy XSD To " + wsdlDirFile.getPath() + "--->" + xsd.getName());
418                 File out = new File(wsdlDirFile + File.separator + xsd.getName());
419                 try {
420                     HelperFileUtil.copyFile(xsd, out);
421                 } catch (IOException ioe) {
422                 	String msg=MESSAGES.getString("CRB000500_Error_accessing_the_WSDL_directory");
423                   LOG.error(msg, ioe);
424                   throw new ClassGenerationException(msg, ioe);
425                 }
426             }
427        
428   }
429 
430   /**
431    * This method is used to generate all the consumer code starting from the
432    * WSDL of the Endpoint to consume.
433    * The consumer code can be generated starting from IDL in case it is included inside WSDL (idl element) 
434    *
435    * Steps:
436    * 1) copy wsdl from url to local directory
437    * 2) check if IDL content is found inside WSDL
438    * 3) call the proper method to generate consumer classes
439    *
440    *
441    * @param wsdlStringUrl   Where the WSDL is located.
442    * @param workdir         Where the method can generate the code.
443    * @param jars            The jar needed at compile time and run time.
444    *
445    * @param All the references to the object generated.
446    *
447    * @throws  ClassGenerationException    When the code cannot be generated.
448    *
449    */
450   	public ServerCorbaClassesHolder generateConsumerServiceClassesDirect(
451           String wsdlStringUrl,
452           String workdir,
453           List<String> jars,
454           JbiServiceDescriptor jbiServiceDescriptor) throws ClassGenerationException {
455 
456       // ========================================
457       // copying wsdl from url to local directory
458       // ========================================
459 
460       File wsdlDirFile = copyWsdlTo(workdir, wsdlStringUrl);
461       //Copy all XSD to work directory
462       //File f=new File(wsdlStringUrl);
463       File f=new File(workdir);
464       String srcDir=f.getParent();
465       //30-06-09 Temporary Fix
466       //ServiceMix fix
467       //Deploy problem after ESB restart phase 
468       copyXSDFile(srcDir,f);
469       copyXSDFile(srcDir,wsdlDirFile);
470       
471       String wsdlDirName = null;
472       try {
473           wsdlDirName = wsdlDirFile.getCanonicalPath();
474       } catch (IOException ioe) {
475           ioe.printStackTrace();
476           String msg = MESSAGES.getString("CRB000500_Error_accessing_the_WSDL_directory");
477           LOG.error(msg, ioe);
478           throw new ClassGenerationException(msg, ioe);
479       }
480 
481       // calling the proper method to generate consumer classes 
482       if (isIdlIncluded(jbiServiceDescriptor)) {
483 			WsdlInformation wsdlInformation = extractWsdlInformation(getWsdlFileName(wsdlDirName));
484 			return generateConsumerServiceClassesDirectFromIDL(wsdlDirFile,
485 					jars, jbiServiceDescriptor, wsdlInformation);
486 		} else {
487 			return generateConsumerServiceClassesDirectFromWSDL(wsdlDirFile,
488 					jars);
489 		}
490   }
491   	
492     /**
493      * This method is used to generate all the consumer code starting from the
494      * WSDL of the Endpoint to consume.
495      *
496      * Steps:
497      * 1) code generation: wsdl to java
498      * 2) compile the new source
499      * 3) bytecode manipultion: the classes must be modified to use rmic
500      * 4) compile with rmic to generate the corba classes
501      * 5) add the getter, setter and serialVersionUID to the class
502      * 6) save all the objects in the ServerCorbaClassesHolder
503      *
504      *
505      * @param wsdlDirFile     Where the WSDL is located.
506      * @param workdir         Where the method can generate the code.
507      * @param jars            The jar needed at compile time and run time.
508      *
509      * @param All the references to the object generated.
510      *
511      * @throws  ClassGenerationException    When the code cannot be generated.
512      *
513      */
514     public ServerCorbaClassesHolder generateConsumerServiceClassesDirectFromWSDL(
515         File wsdlDirFile,
516         List<String> jars) throws ClassGenerationException {
517 
518         LOG.debug(">>>>> generateConsumerServiceClassesDirectWSDL - begin");
519 
520         String wsdlDirName = null;
521         try {
522             wsdlDirName = wsdlDirFile.getCanonicalPath();
523         } catch (IOException ioe) {
524         	ioe.printStackTrace();
525         	String msg=MESSAGES.getString("CRB000500_Error_accessing_the_WSDL_directory");
526             LOG.error(msg, ioe);
527             throw new ClassGenerationException(msg, ioe);
528         }
529         
530         // ==========================
531         //     add orb.idl and ir.idl
532         // ==========================
533         copyOrbIrIdl(wsdlDirName);
534 
535         // ==================================================
536         //                preparing directory (src + classes)
537         // ==================================================
538         String sourceDirName = mkdir(wsdlDirFile, "src");
539         final String classesDirName = mkdir(wsdlDirFile, "classes");
540 
541         // =======================================
542         // generating source files  (WSDL to JAVA)
543         // =======================================
544         WsdlInformation wsdlInformation
545           = wsdlToJava(wsdlDirName, sourceDirName, jars);
546 
547         List<QName> portTypeList = wsdlInformation.getPortTypeList();
548 
549         // ======================
550         // compiling java classes
551         // ======================
552         javac(sourceDirName, classesDirName, jars);
553 
554         // ===============================
555         // finding <Service>PortType.class
556         // ===============================
557         //String portTypeClassName = findingPortTypeClassName(classesDirName);
558         String portTypeClassName
559                 = findingPortTypeClassName(portTypeList, classesDirName);
560         
561         // ========================================
562         // ByteCode Manipulation:
563         // add the correct exceptions to the throws clause
564         // of the remote interface (the generated interface
565         // throws a FaultInfoException).
566         // Decomment when working on issue CRB-118 
567         //=========================================        
568         // tweakRemoteInterfaceGeneratedFromWSDL(portTypeClassName,
569         //                                       classesDirName); 
570 
571         // ========================================
572         // ByteCode Manipulation: add Remote
573         //=========================================
574         String remoteClassName = tweakInterfaceClasses(portTypeClassName,
575                                                        classesDirName);
576 
577         // ========================================
578         // ByteCode Manipulation: valuetype
579         // ========================================
580         List<String> modifiedClassNames
581           = tweakValueType(remoteClassName, classesDirName);
582 
583 //        Map<String, AnnotationsMaps> annota = tweakAnnotationCollector(
584 //          modifiedClassNames, classesDirName);
585 //
586 //        for (String currentClass : annota.keySet()) {
587 //            AnnotationsMaps tracer = annota.get(currentClass);
588 //
589 //            LOG.debug("TRACER. currentClass=" + currentClass
590 //              + "; tracer=" + tracer);
591 //        }
592 
593         //Map<String, String> smap = tweakSerialVersionUID(modifiedClassNames, classesDirName);
594         //Util.debug("SVUID", smap);
595 
596         // =======================
597         // instantiate class loader
598         // =======================
599         URLClassLoader urlClassLoader = getURLClassLoader(classesDirName);
600         LOG.debug("instantiate class loader ... done");
601 
602         // =================================================================
603         // Generating the skeleton using the class file instead of the IDLs.
604         // =================================================================
605         String newSourceCode
606           = Util.generateImplementationClass(urlClassLoader, remoteClassName, true);
607 
608         String newSourcePath
609           = remoteClassName.replace('.', File.separatorChar) + "Impl";
610 
611         LOG.debug("newSourcePath=["
612             + sourceDirName + File.separatorChar + newSourcePath + "]");
613 
614         File newSourceFile
615           = Util.saveAsJavaSource(newSourceCode, sourceDirName, newSourcePath);
616 
617         List<String> extra = new ArrayList<String>();
618         extra.add(classesDirName);
619 
620         List<String> newSourceList = new ArrayList<String>();
621         newSourceList.add(newSourceFile.getAbsolutePath());
622         Util.compileJavaClasses(sourceDirName,
623                                 classesDirName,
624                                 newSourceList,
625                                 jars,
626                                 extra);
627 
628         Util.compileRemoteClassesNoValueMethodsON(classesDirName,
629                                                   remoteClassName + "Impl",
630                                                   extra);
631 
632         List<String> newPathList = add(classesDirName, modifiedClassNames);
633         Map<Long, String> uidMap
634           = Util.extractSerialVersionUid(classesDirName, newPathList);
635         //Util.debug("UID", uidMap);
636 
637         // =================================
638         //  ADAPTING AUTOGENERATED VALUETYPE
639         // =================================
640         tweakWsdlToCorba(modifiedClassNames, classesDirName);
641         LOG.debug("end creating java sources implementation for value types.");
642         tweakUID(uidMap);
643 
644         //tweakAnnotationWriter(classesDirName, annota);
645 
646         //now we need the following classes
647 
648         // NEW poaTie (e.g.: _EchoSCServicePortTypeCorbaInterfaceImpl_Tie.class)
649         int lastDot = remoteClassName.lastIndexOf(".");
650         String poaPackage = remoteClassName.substring(0, lastDot);
651         String poaName = "_" + remoteClassName.substring(lastDot + 1)
652                        + "Impl_Tie";
653         String poaTie     = poaPackage + "." + poaName;
654 
655         // Takes the service of the first port type
656         QName serviceName
657           = extractServiceNameFromPortType(wsdlDirName, portTypeList.get(0));
658         String portTypePackage
659           = portTypeClassName.substring(0, portTypeClassName.lastIndexOf('.'));
660         QName portTypeName = portTypeList.get(0);
661         
662         // String serviceImpl = portTypePackage + "." + serviceName.getLocalPart() + "Impl";
663         String serviceImpl = portTypePackage + "." + portTypeName.getLocalPart() + "CorbaInterfaceImpl";
664 
665         LOG.debug("poaTie=" + poaTie + "; serviceImpl=" + serviceImpl);
666 
667         ServerCorbaClassesHolder serverCorbaClassesHolder
668             = new ServerCorbaClassesHolder();
669 
670         // =======================
671         // instantiate class loader (Refresh URLClassLoader
672         // =======================
673         urlClassLoader = getURLClassLoader(classesDirName);
674         LOG.debug("instantiate class loader ... done");
675 
676         setCorbaOperations(serverCorbaClassesHolder,
677                            urlClassLoader,
678                            remoteClassName);
679 
680         setCorbaPOATie(serverCorbaClassesHolder, urlClassLoader, poaTie);
681 
682         setCorbaImpl(serverCorbaClassesHolder,
683                         urlClassLoader,
684                         remoteClassName + "Impl");
685 
686         setWebServiceInterface(serverCorbaClassesHolder,
687                                urlClassLoader,
688                                portTypeClassName);
689         //setCorbaHelper(serverCorbaClassesHolder, urlClassLoader, helper);
690 
691         serverCorbaClassesHolder.setUrlClassLoader(urlClassLoader);
692 
693         setWebServiceImpl(serverCorbaClassesHolder,
694                           urlClassLoader,
695                           serviceImpl);
696 
697         serverCorbaClassesHolder.setWsdlInformation(wsdlInformation);
698 
699         LOG.debug("<<<<< generateConsumerServiceClasses - end");
700         return serverCorbaClassesHolder;
701     }
702 
703     /**
704      * This method is used to generate all the consumer code starting from the
705      * IDL found inside the WSDL of the Endpoint to consume.
706      *
707      *
708      * @param wsdlDirFile     Dir where the WSDL is located.
709      * @param idlContent      Content of the idl file extracted previously from WSDL
710      * @param workdir         Where the method can generate the code.
711      * @param jars            The jar needed at compile time and run time.
712      *
713      * @param All the references to the object generated.
714      *
715      * @throws  ClassGenerationException    When the code cannot be generated.
716      *
717      */
718     public ServerCorbaClassesHolder generateConsumerServiceClassesDirectFromIDL(
719         File wsdlDirFile,
720         List<String> jars,
721         JbiServiceDescriptor jbiServiceDescriptor,
722         WsdlInformation wsdlInformation) 
723     	throws ClassGenerationException {
724     	
725         String wsdlDirName = null;
726         try {
727             wsdlDirName = wsdlDirFile.getCanonicalPath();
728         } catch (IOException ioe) {
729         	ioe.printStackTrace();
730         	String msg=MESSAGES.getString("CRB000500_Error_accessing_the_WSDL_directory");
731             LOG.error(msg, ioe);
732             throw new ClassGenerationException(msg, ioe);
733         }
734     	
735 		ProviderServiceClassesGenerator serviceGenerator = new ProviderServiceClassesGenerator();
736 		ArrayList<JbiServiceDescriptor> serviceDescriptorList=new ArrayList<JbiServiceDescriptor>();
737         ArrayList<String> portTypeNameList= new ArrayList<String>();
738         serviceDescriptorList.add(jbiServiceDescriptor);
739         
740         portTypeNameList.add(wsdlInformation.getPortTypeList().get(0).getLocalPart());
741         
742         List<ClientCorbaClassesHolder> classes = serviceGenerator.generateProviderServiceClasses(serviceDescriptorList, wsdlDirName, jars, portTypeNameList);
743     	
744         ServerCorbaClassesHolder serverCorbaClassesHolder  = generateConsumerCorbaClassesHolder(wsdlDirName, jars, classes, serviceGenerator,jbiServiceDescriptor);
745         serverCorbaClassesHolder.setWsdlInformation(wsdlInformation);
746         serverCorbaClassesHolder.setGenerateClassesFromIDL(true);
747         return serverCorbaClassesHolder;
748 		
749     }
750  
751     /**
752      * This method is used to generate all the consumer code starting from the
753      * classes already generated with provider class generation API.
754      *
755      * @param serviceGenerator  ProviderServiceClassesGenerator
756      * @param classes      		ClientCorbaClassesHolder
757      * @param workdir         	Where the method can generate the code.
758      * @param jars            	The jar needed at compile time and run time.
759      *
760      * @return All the references to the object generated.
761      *
762      * @throws  ClassGenerationException    When the code cannot be generated.
763      *
764      */
765     public ServerCorbaClassesHolder generateConsumerCorbaClassesHolder(
766     		String workdir,
767     		List<String> jars,
768     		List<ClientCorbaClassesHolder> classes,
769     		ProviderServiceClassesGenerator serviceGenerator,
770                 JbiServiceDescriptor jbidesc
771                 )
772     		throws ClassGenerationException
773     {
774         //Index is used for the correct interface selection
775     	int index=0; 
776     	String workdirsrc = workdir + "/src";
777     	
778     	// The implementation class must be created in the classes directory that 
779     	// generates the corba servant. 
780     	String implementationDirClasses = workdir + "/origclasses";
781         
782         String operationsClassNameFullName="";
783         //List<File> operationsClass = Util.findFilesFromSourceDirectory(implementationDirClasses, "Operations.class");
784         String operationsClassName="";
785         try {
786             // (dir) + pkg + name + .class
787                 if(classes.size()>1){
788 
789                     for(int i=0;i<classes.size();i++){
790                   //select the class by the name
791                         String operationClassName=classes.get(i).getOperationsClass().getName();
792                         LOG.debug("operationClassName: "+operationClassName);
793                         int start=operationClassName.lastIndexOf(".")+1;
794                         int end =operationClassName.lastIndexOf("Operations");
795                         LOG.debug("Extracted string: "+operationClassName.substring(start, end));
796                         LOG.debug("PortTypeLocalPart: "+jbidesc.getPortTypeName().getLocalPart());
797                          if (jbidesc.getPortTypeName().getLocalPart().equals(operationClassName.substring(start, end))) {
798                             operationsClassNameFullName = new File(implementationDirClasses+File.separator+operationClassName.replace(".", File.separator)+".class").getCanonicalPath();
799                             LOG.debug("operationsClassFileNameFullName: "+operationsClassNameFullName+" index: "+i);
800                             //LOG.debug(i+"simo ClientCorbaClassesHolder: "+classes.get(i));
801                             //LOG.debug("operationsClass: "+Arrays.toString(operationsClass.toArray()));
802                             //LOG.debug("ClientCorbaHolderList: "+Arrays.toString(classes.toArray()));
803                             //if there are many interface it select the correct interface
804                             index=i;
805                         break;
806                         }
807                     }
808                 } 
809                 else{
810                     String operationClassName=classes.get(0).getOperationsClass().getName();
811                     operationsClassNameFullName = new File(implementationDirClasses+File.separator+operationClassName.replace(".", File.separator)+".class").getCanonicalPath();
812                     index=0;
813                 }
814         	LOG.debug("Operation Class Name -->"+operationsClassNameFullName);
815         	operationsClassName
816                 = operationsClassNameFullName.substring(
817                 		implementationDirClasses.length() + 1,
818                 		operationsClassNameFullName.length() - ".class".length());
819             operationsClassName
820                 = operationsClassName.replace('/', '.').replace('\\', '.');
821             LOG.debug("finding Operation classes - " + operationsClassName);
822         } catch (IOException e) {
823             Object[] args = new Object[] { classes.get(index).getOperationsClass().getName() };
824             LOG.error("CRB000503_Error_getting_name", args, e);
825             throw new ClassGenerationException(
826                     "CRB000503_Error_getting_name", args, e);
827         }
828         
829         String classRoot = operationsClassName.substring(0, operationsClassName.lastIndexOf("Operations"));
830         String poaTieClassName     	= classRoot + "POATie";
831         String helperClassName     	= classRoot + "Helper";        
832 
833 		// =======================
834 		// instantiate class loaders
835 		// =======================
836 
837         URLClassLoader urlClassLoader = serviceGenerator.getUrlClassLoader();
838 		
839 		URLClassLoader originalClassLoader = serviceGenerator
840 				.getOriginalClassLoader();				
841 		
842 		LOG.debug("Obtained class loaders (original and modified) ... done");		
843         
844         // =================================================================
845         // Generating the Impl class
846         // =================================================================
847         String serviceImplClassName = operationsClassName + "Impl";
848         
849         // Generates the implementation class and saves it
850         String newSourceCode = Util.generateImplementationClass(originalClassLoader, operationsClassName, false);                
851         String newSourcePath = operationsClassName.replace('.', File.separatorChar) + "Impl";
852         LOG.debug("newSourcePath=[" + implementationDirClasses + File.separatorChar + newSourcePath + "]");
853         File newSourceFile = 
854         	Util.saveAsJavaSource(newSourceCode, workdirsrc, newSourcePath);              
855         List<String> extra = new ArrayList<String>();
856         extra.add(implementationDirClasses);
857 
858         List<String> newSourceList = new ArrayList<String>();
859         newSourceList.add(newSourceFile.getAbsolutePath());
860         // Compiles the generated source 
861         Util.compileJavaClasses(workdirsrc,
862         		implementationDirClasses,
863                                 newSourceList,
864                                 jars,
865                                 extra);
866 
867         LOG.debug("=======================================================================");
868         LOG.debug("                     CONSUMER CLASS ASSOCIATION                        ");
869         LOG.debug("=======================================================================");
870         LOG.debug("Operation Class Name -->"+classes.get(index).getOperationsClass().getName());
871         LOG.debug("POA TIE  NAME -->"+poaTieClassName);
872         LOG.debug("SERVICE CLASS  NAME -->"+serviceImplClassName);
873         LOG.debug("=======================================================================");
874         LOG.debug("                    END CONSUMER CLASS GENERATION                      ");
875         LOG.debug("=======================================================================");
876         // Creates the ServerCorbaClassesHolder to put into the genrated classes
877         ServerCorbaClassesHolder serverCorbaClassesHolder  = new ServerCorbaClassesHolder();
878         
879         setCorbaOperations(serverCorbaClassesHolder, originalClassLoader, operationsClassName);
880         setCorbaPOATie(serverCorbaClassesHolder, originalClassLoader, poaTieClassName);        
881         setCorbaImpl(serverCorbaClassesHolder, originalClassLoader,serviceImplClassName);
882         setWebServiceInterface(serverCorbaClassesHolder, originalClassLoader,operationsClassName);
883         setCorbaHelper(serverCorbaClassesHolder, originalClassLoader, helperClassName);
884         serverCorbaClassesHolder.setUrlClassLoader(originalClassLoader);
885         // The WebService interface generated in the ClassesGeneration
886         serverCorbaClassesHolder.setWebServiceImpl(classes.get(index).getOperationsClass());        
887         // All the metadata stuff collected for the runtime part.
888 	serverCorbaClassesHolder.setValueTypeIdAndInstance(classes.get(index).getValueTypeIdAndInstance());
889 	serverCorbaClassesHolder.setMethodSignatures(classes.get(index).getMethodSignatures());
890 	serverCorbaClassesHolder.setAllUniontypes(classes.get(index).getAllUnionTypesMap());
891 	serverCorbaClassesHolder.setSubstitutedUnionFields(classes.get(index).getSubstitutedUnionFields());
892 	serverCorbaClassesHolder.setAllInterfacetypes(classes.get(index).getAllInterafceTypesMap());
893 	serverCorbaClassesHolder.setSubstitutedInterfaceFields(classes.get(index).getSubstitutedInterfaceFields());
894 	serverCorbaClassesHolder.setAllIDLTypes(classes.get(index).getAllIDLTypes());
895 	serverCorbaClassesHolder.setCorbaEnumMap(classes.get(index).getCorbaEnumMap());	
896         serverCorbaClassesHolder.setIdToClassNameMap(classes.get(index).getIdToClassMap());
897 	serverCorbaClassesHolder.setUrlClassLoader(urlClassLoader);
898 	serverCorbaClassesHolder.setOriginalClassLoader(originalClassLoader);
899 	serverCorbaClassesHolder.setTypeDefs(classes.get(index).getTypeDefs());
900                 
901 	return serverCorbaClassesHolder;
902     }
903     
904     
905     /**
906      * Adds the basedir to the pathList.    
907      * @param dir
908      * @param pathList
909      * @return
910      */
911     private List<String> add(String dir, List<String> pathList) {
912       List<String> newPathList = new ArrayList<String>();
913 
914       if (pathList == null || pathList.size() == 0) {
915         return newPathList;
916       }
917 
918       String basedir = null;
919       if (dir == null) {
920         basedir = "";
921       } else {
922         basedir = dir;
923       }
924 
925       for (String path : pathList) {
926         String np = basedir + File.separator
927                             + path.replace('.', File.separatorChar)
928                             + ".class";
929         newPathList.add(np);
930         LOG.debug("NEWPATH=" + np);
931       }
932       return newPathList;
933     }
934 
935     /**
936      * This method changes the bytecode of some class to avoid abstract
937      * declaration of the valuetype.
938      *
939      * @param remoteClassName   The class inspected to find the value types
940      * @param classesDirName    The directory of the classes files
941      * 
942      * @return  The return
943      *
944      * @throws ClassGenerationException    The class generation exception
945      */
946     private List<String> tweakValueType(String remoteClassName,
947       String classesDirName) throws ClassGenerationException {
948 
949         LOG.debug("CRB000555_tweakValueType_begin");
950 
951         List<String> javaClassNameOfTheModifiedClasses = new ArrayList<String>();
952 
953         String cn = remoteClassName.replace('.', File.separator.charAt(0));
954 
955         List<File> classList = new ArrayList<File>();
956         classList.add(new File(classesDirName + File.separator + cn));
957 
958         Set<Class> classesToChange
959             = Util.findClassUsed(classesDirName, classList);
960 
961         // for each class that represent a valuetype ...
962         for (Class c : classesToChange) {
963             // ... extracting the class name of the class to manipulate
964             String className = classesDirName
965                             + File.separator
966                             + c.getName().replace('.', '/')
967                             + ".class";
968             LOG.debug("CRB000556_tweakValueType_class", new Object[]{className});
969 
970             javaClassNameOfTheModifiedClasses.add(c.getName());
971 
972             // ... preparing the object for the bytecode manipulation
973             ClassWriter  cw = new ClassWriter(true); // visitMaxs
974             ClassVisitor cc = new CheckClassAdapter(cw);
975             StringWriter sw = new StringWriter();
976             ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
977 
978             ClassAdapter cv = new ValueTypeAdapter(tv, cw, className);
979 
980             ClassReader cr = Util.getAsmCLassReader(className);
981             LOG.debug("getAsmCLassReader ... done");
982 
983             // ... execute
984             cr.accept(cv, true);
985             LOG.debug("ClassReader.accept ... done");
986 
987             if (LOG.isDebugEnabled()) {
988                 LOG.debug("output of tracer during creation of class: "
989                         + className + "\n" + sw.toString());
990             }
991 
992             // ...extracting the new bytecode
993             byte [] newBytecode = cw.toByteArray();
994 
995             // ... and replace the old class
996             String relativeFileName = className.replace('/', File.separatorChar);
997             Util.saveAsJavaClass(relativeFileName, newBytecode);
998         }
999 
1000         LOG.debug("<<<<< tweakValueType - end");
1001         return javaClassNameOfTheModifiedClasses;
1002     }
1003 
1004 //    /**
1005 //     * XXX javadoc.
1006 //     * 
1007 //     * @param list The list
1008 //     * @param classesDirName  The class dir name
1009 //     * @throws ClassGenerationException  The class generation exception
1010 //     * @return  A map where the key is a class name and the value is an object
1011 //     *          that contains all the annotations of the associated class.
1012 //     */
1013 //    private Map<String, AnnotationsMaps> tweakAnnotationCollector(
1014 //      List<String> list,String classesDirName) throws ClassGenerationException {
1015 //
1016 //      LOG.debug(">>>>> tweakAnnotationCollector - begin");
1017 //
1018 //      Map<String, AnnotationsMaps> annotationTracerMap
1019 //        = new HashMap<String, AnnotationsMaps>();
1020 //
1021 //      ClassAdapter cv = null;
1022 //
1023 //      // for each class to modify ...
1024 //      for (String currentClassName : list) {
1025 //        String fullPath = classesDirName
1026 //                        + File.separator
1027 //                        + currentClassName.replace('.', '/')
1028 //                        + ".class";
1029 //
1030 //        LOG.debug("tweakAnnotationCollector for " + fullPath);
1031 //
1032 //        // ... preparing the object for the bytecode manipulation
1033 //        ClassWriter  cw = new ClassWriter(true); // visitMaxs
1034 //        ClassVisitor cc = new CheckClassAdapter(cw);
1035 //        StringWriter sw = new StringWriter();
1036 //        ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
1037 //
1038 //        AnnotationsMaps annotationTracer = new AnnotationsMaps();
1039 //
1040 //        cv = new AnnotationCollectorAdapter(tv,
1041 //                                   cw,
1042 //                                   fullPath,
1043 //                                   annotationTracer,
1044 //                                   currentClassName);
1045 //
1046 //        annotationTracerMap.put(currentClassName, annotationTracer);
1047 //
1048 //        ClassReader cr = Util.getAsmCLassReader(fullPath);
1049 //        LOG.debug("getAsmCLassReader ... done");
1050 //
1051 //        // ... execute
1052 //        cr.accept(cv, true);
1053 //        LOG.debug("ClassReader.accept ... done");
1054 //
1055 //      }
1056 //
1057 //      LOG.debug("<<<<< tweakAnnotationCollector - end");
1058 //      return annotationTracerMap;
1059 //    }
1060 
1061 
1062 //    /**
1063 //     * XXX javadoc.
1064 //     * 
1065 //     * @param classesDirName  The class dir name
1066 //     * @param annota  The annotation map
1067 //     * @throws ClassGenerationException The class generation exception
1068 //     */
1069 //    private void tweakAnnotationWriter(String classesDirName,
1070 //      Map<String, AnnotationsMaps> annota) throws ClassGenerationException {
1071 //
1072 //      LOG.debug(">>>>> tweakAnnotationWriter - begin");
1073 //
1074 //      // for each class with annotations ...
1075 //      for (String javaClassName : annota.keySet()) {
1076 //          // ... extracting the class name of the class to manipulate
1077 //          String fullPath = classesDirName
1078 //                          + File.separator
1079 //                          + javaClassName.replace('.', '/')
1080 //                          + ".class";
1081 //
1082 //        LOG.debug("tweakAnnotationWriter for " + fullPath);
1083 //
1084 //        // ... preparing the object for the bytecode manipulation
1085 //        ClassWriter  cw = new ClassWriter(true); // visitMaxs
1086 //        ClassVisitor cc = new CheckClassAdapter(cw);
1087 //        StringWriter sw = new StringWriter();
1088 //        ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
1089 //
1090 //        ClassAdapter cv
1091 //          = new AnnotationWriterAdapter(tv, annota.get(javaClassName));
1092 //
1093 //        ClassReader cr = Util.getAsmCLassReader(fullPath);
1094 //        LOG.debug("getAsmCLassReader ... done");
1095 //
1096 //        // ... execute
1097 //        cr.accept(cv, true);
1098 //        LOG.debug("ClassReader.accept ... done");
1099 //
1100 //        if (LOG.isDebugEnabled()) {
1101 //            LOG.debug("output of tracer during creation of class: "
1102 //                    + fullPath + "\n" + sw.toString());
1103 //        }
1104 //
1105 //        // ...extracting the new bytecode
1106 //        byte [] newBytecode = cw.toByteArray();
1107 //
1108 //        // ... and replace the old class
1109 //        String absoluteFileName = fullPath.replace('/', File.separatorChar);
1110 //        Util.saveAsJavaClass(absoluteFileName, newBytecode);
1111 //      }
1112 //
1113 //      LOG.debug("<<<<< tweakAnnotationWriter - end");
1114 //    }
1115 
1116 //    /**
1117 //     * XXX javadoc.
1118 //     * 
1119 //     * @param javaName  The java name
1120 //     * @param newBasedir  The new base dir
1121 //     * @return  The return
1122 //     */
1123 //    private List<String> exctractJavaListJavaName(
1124 //            List<String> javaName, String newBasedir) {
1125 //
1126 //            List<String> result = new ArrayList<String>();
1127 //
1128 //            if (javaName != null) {
1129 //                for (String current : javaName) {
1130 //                    // (dir) + (pkg.name) + (.java)
1131 //                    String j = newBasedir
1132 //                            + File.separator
1133 //                            + current.replace('.', '/')
1134 //                            + ".java";
1135 //
1136 //                    LOG.debug("exctractJavaListJavaName:" + j);
1137 //                    result.add(j);
1138 //                }
1139 //            }
1140 //
1141 //            return result;
1142 //    }
1143 
1144 
1145     /**
1146      * This method manipulate the bytecode to comply Corba specifications.
1147      *
1148      * @param    files           The list of IDL files used to deduce
1149      *                           the name of the class to manipulate.
1150      * @param    classesDirName  The class dir name
1151      *
1152      * @throws ClassGenerationException  The class generation exception
1153      *
1154      */
1155     private void tweakWsdlToCorba(
1156       List<String> files,
1157       String classesDirName) throws ClassGenerationException {
1158 
1159         LOG.debug(">>>>>>>>>> tweakAdapting - begin");
1160 
1161         if (files == null || files.size() == 0) {
1162             LOG.debug("<<<<<<<<<< tweakAdapting - end."
1163                     + "No files to manipulate.");
1164             return;
1165         }
1166 
1167         // else
1168 
1169         // for each valuetype ...
1170         for (String vt : files) {
1171 
1172             // (dir) + (pkg.name) + (.class)
1173             String className = classesDirName
1174                             + File.separator
1175                             + vt.replace('.', '/')
1176                             + ".class";
1177 
1178             ClassWriter  cw = new ClassWriter(true); // visitMaxs
1179             ClassVisitor cc = new CheckClassAdapter(cw);
1180             StringWriter sw = new StringWriter();
1181             ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
1182 
1183             ClassAdapter cv
1184               = new WsdlToCorbaAdapter(tv, cw, className, classesDirName);
1185 
1186             ClassReader cr = Util.getAsmCLassReader(className);
1187             LOG.debug("getAsmCLassReader ... done");
1188 
1189             cr.accept(cv, true);
1190             LOG.debug("ClassReader.accept ... done");
1191 
1192             LOG.debug("output of tracer during creation of class: "
1193                     + className + "\n" + sw.toString());
1194 
1195             byte [] newBytecode = cw.toByteArray();
1196 
1197             // write class in the right place
1198             String relativeFileName = className.replace('/', File.separatorChar);
1199             Util.saveAsJavaClass(relativeFileName, newBytecode);
1200         }
1201 
1202         LOG.debug("<<<<<<<<<< tweakAdapting - end");
1203     }
1204 
1205     private void tweakUID(Map<Long, String> uidPathMap)
1206       throws ClassGenerationException {
1207 
1208       LOG.debug(">>>>>>>>>> tweakUID - begin");
1209 
1210       if (uidPathMap == null || uidPathMap.size() == 0) {
1211           LOG.debug("<<<<<<<<<< tweakUID - end."
1212                   + "No files to manipulate.");
1213           return;
1214       }
1215 
1216       // else
1217 
1218       // for each valuetype ...
1219       for (Long uid : uidPathMap.keySet()) {
1220 
1221         String path = uidPathMap.get(uid);
1222         LOG.debug("tweakUID. path=" + path + "; uid=" + uid);
1223 
1224         ClassWriter  cw = new ClassWriter(true); // visitMaxs
1225         ClassVisitor cc = new CheckClassAdapter(cw);
1226         StringWriter sw = new StringWriter();
1227         ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
1228 
1229         ClassAdapter cv = new UIDAdapter(tv, cw, uid);
1230 
1231         ClassReader cr = Util.getAsmCLassReader(path);
1232         LOG.debug("tweakUID. getAsmCLassReader ... done");
1233 
1234         cr.accept(cv, true);
1235         LOG.debug("tweakUID. ClassReader.accept ... done");
1236 
1237         LOG.debug("tweakUID. output of tracer during creation of class: "
1238                 + path + "\n" + sw.toString());
1239 
1240         byte [] newBytecode = cw.toByteArray();
1241 
1242         // write class in the right place
1243         Util.saveAsJavaClass(path, newBytecode);
1244       }
1245 
1246       LOG.debug("<<<<<<<<<< tweakAdapting - end");
1247     }
1248 
1249 
1250     /**
1251      * Copy all the IDLs with care about (sub)path.
1252      *
1253      * @param    classesDirName    The directory where we can find the IDL files.
1254      * @param    wsdlDirName        The directory where we copy he IDL files.
1255      * @param    remoteClassName    The remote class name.
1256      *
1257      * @return    The list of the IDL files in classesDirName.
1258      *
1259      * @throws    ClassGenerationException  The class generation exception
1260      */
1261     public List<String> copyIDLs(
1262         String classesDirName,
1263         String wsdlDirName,
1264         String remoteClassName) throws ClassGenerationException {
1265 
1266         LOG.debug(">>>>> copyIDLs - begin");
1267 
1268         // remoteClassName: full class name without the '.class'
1269 
1270         String idlFilename = classesDirName + File.separator
1271             + remoteClassName.replace('.', File.separatorChar)
1272             + ".idl";
1273 
1274         String destIdlFileName
1275             = wsdlDirName + File.separator
1276             + remoteClassName.substring(remoteClassName.lastIndexOf('.') + 1)
1277             + ".idl";
1278 
1279         copyFile(idlFilename, destIdlFileName);
1280 
1281         List<String> idls = null;
1282         try {
1283 
1284             idls = Util.findIdlFiles(classesDirName);
1285 
1286         } catch (Jbi4CorbaException e) {
1287             LOG.error(e.getMessage(), e);
1288             throw new ClassGenerationException(e.getMessage(),e);
1289         }
1290 
1291         // creating the directory of the package
1292         File wf = new File(wsdlDirName);
1293         for (int i = 0; i < (idls == null ? 0 : idls.size()); i++) {
1294             LOG.debug("copying idls[" + i + "]=" + idls.get(i));
1295 
1296             if (idls.get(i).equals(idlFilename)) {
1297 
1298                 LOG.debug("already copied:" + idls.get(i));
1299 
1300             } else {
1301                 String pkgAsDir = subBasedir(idls.get(i), classesDirName);
1302 
1303                 mkdir(wf, pkgAsDir);
1304 
1305                 String fn = pkgAsDir + File.separator
1306                         + new File(idls.get(i)).getName();
1307 
1308                 copyFile(classesDirName + File.separator + fn,
1309                         wsdlDirName    + File.separator + fn);
1310             }
1311 
1312         }
1313 
1314         LOG.debug("<<<<< copyIDLs - end");
1315         return idls;
1316     }
1317 
1318 
1319     /**
1320      * Remove the base dir in the directory class name.
1321      *
1322      * @param    fullFilename    Canonical file name of the file
1323      * @param    basedir         The basedir
1324      *
1325      * @return    The result.
1326      */
1327     private String subBasedir(String fullFilename, String basedir) {
1328         // full = basedir + pkg + filename.idl
1329         LOG.debug(">>>>> subBasedir - begin");
1330         String s = fullFilename.substring(basedir.length() + 1);
1331 
1332         int limit = s.lastIndexOf(File.separator);
1333 
1334         s = s.substring(0, limit);
1335 
1336         LOG.debug("<<<<< subBasedir - end:" + s);
1337         return s;
1338     }
1339 
1340 
1341 
1342 
1343     /**
1344      * @param portTypesList  The port types list
1345      * @param classesDirName  The class dir name
1346      * @throws ClassGenerationException  The class generation exception
1347      * @return  The full java class name (package + class).
1348      */
1349     private String findingPortTypeClassName(List<QName> portTypesList,
1350         String classesDirName) throws ClassGenerationException {
1351 
1352         LOG.debug(">>>>> finding portTypeClassName - begin");
1353 
1354         int size = (portTypesList == null) ? 0 : portTypesList.size();
1355         if (size != 1) {
1356             LOG.error("CRB000504_Expected_exactly_one_class", size);
1357             throw new ClassGenerationException(
1358                     "CRB000504_Expected_exactly_one_class",
1359                     new Object[] { size }, null);
1360         }
1361 
1362         String c = portTypesList.get(0).getLocalPart() + ".class";
1363         //String p = portTypesList.get(0).getNamespaceURI().replace('.', '/');
1364 
1365         // FIXME what happen if I have 2 classes with the same name but
1366         //       different package.
1367         List<File> portTypeClasses = Util.findFilesFromSourceDirectory(
1368                 classesDirName, c);
1369 
1370         if (portTypeClasses.size() != 1) {
1371             LOG.error("CRB000505_PortType_class_not_found", c);
1372             throw new ClassGenerationException(
1373                     "CRB000505_PortType_class_not_found", new Object[] { c },
1374                     null);
1375         } else {
1376             LOG.debug("PortType class not found:" + portTypeClasses.get(0));
1377         }
1378 
1379         String portTypeClassName;
1380         try {
1381             // (dir) + pkg + name + .class
1382             portTypeClassName = portTypeClasses.get(0).getCanonicalPath();
1383 
1384             portTypeClassName
1385                 = portTypeClasses.get(0).getCanonicalPath().substring(
1386                         classesDirName.length() + 1,
1387                         portTypeClassName.length() - ".class".length());
1388 
1389             portTypeClassName
1390                 = portTypeClassName.replace('/', '.').replace('\\', '.');
1391 
1392             LOG.debug("finding PortType class - " + portTypeClassName);
1393         } catch (IOException e) {
1394             Object[] args = new Object[] { portTypeClasses.get(0) };
1395 
1396             LOG.error("CRB000503_Error_getting_name", args, e);
1397             throw new ClassGenerationException(
1398                     "CRB000503_Error_getting_name", args, e);
1399         }
1400 
1401         LOG.debug("<<<<< finding portTypeClassName - end");
1402         return portTypeClassName;
1403     }
1404 
1405     /**
1406      * XXX javadoc.
1407      * 
1408      * @param sourceDirName  The source dir name
1409      * @param classesDirName  The classes dir name
1410      * @param jarFilesName  The jar files name
1411      * @return  The return
1412      * @throws ClassGenerationException  The class generation exception
1413      */
1414     private List<String> javac(
1415         String sourceDirName,
1416         String classesDirName,
1417         List<String> jarFilesName) throws ClassGenerationException {
1418 
1419         LOG.debug(">>>>> javac - begin");
1420         List<String> sources;
1421         try {
1422 
1423             sources = Util.findJavaSources(sourceDirName);
1424 
1425         } catch (Jbi4CorbaException e) {
1426             Object[] args = new Object[] { sourceDirName, e.getMessage() } ;
1427 
1428             String msg=MESSAGES.getString("CRB000501_Error_generating_sources_list",
1429         			new java.lang.Object[] {args}, new java.lang.Object[] {e});
1430             LOG.error(msg);
1431             throw new ClassGenerationException(msg);
1432         }
1433         LOG.debug("compiling java classes - sources found");
1434 
1435         Util.compileJavaClasses(sourceDirName,
1436                                 classesDirName,
1437                                 sources,
1438                                 jarFilesName,
1439                                 null);
1440 
1441         LOG.debug("<<<<< javac - end");
1442         return sources;
1443     }
1444 
1445 /**
1446  * 
1447  * @param serverCorbaClassesHolder   The server corba classes holder
1448  * @param urlClassLoader             The url class loader
1449  * @param helper                     The helper
1450  * @throws ClassGenerationException  The class generation exception
1451  */
1452     private void setCorbaHelper(
1453         ServerCorbaClassesHolder serverCorbaClassesHolder,
1454         URLClassLoader urlClassLoader,
1455         String helper) throws ClassGenerationException {
1456 
1457         LOG.debug(">>>>> setCorbaHelper - begin");
1458         try {
1459             serverCorbaClassesHolder.setCorbaHelper(
1460                     urlClassLoader.loadClass(helper));
1461 
1462         } catch (ClassNotFoundException e) {
1463             Object[] args
1464                     = new Object[] { "setCorbaHelper", helper, urlClassLoader };
1465 
1466             LOG.error("CRB000506_Error_during_method", args, e);
1467             throw new ClassGenerationException(
1468                     "CRB000506_Error_during_method", args, e);
1469         }
1470         LOG.debug("<<<<< setCorbaHelper - end");
1471     }
1472 
1473 
1474   /**
1475    * 
1476    * @param serverCorbaClassesHolder   The server corba classes holder
1477    * @param urlClassLoader             The url class loader
1478    * @param portType                   The port type
1479    * @throws ClassGenerationException  The class generation exception
1480    */
1481     private void setWebServiceInterface(
1482         ServerCorbaClassesHolder serverCorbaClassesHolder,
1483         URLClassLoader urlClassLoader,
1484         String portType) throws ClassGenerationException {
1485 
1486         LOG.debug(">>>>> setWebServiceInterface - begin");
1487         try {
1488             serverCorbaClassesHolder.setWebServiceInterface(
1489                     urlClassLoader.loadClass(portType));
1490 
1491         } catch (ClassNotFoundException e) {
1492             Object[] args = new Object[] {
1493                     "setWebServiceInterface", portType, urlClassLoader };
1494 
1495             LOG.error("CRB000506_Error_during_method", args, e);
1496             throw new ClassGenerationException(
1497                     "CRB000506_Error_during_method", args, e);
1498         }
1499         LOG.debug("<<<<< setWebServiceInterface - end");
1500     }
1501 
1502  /**
1503   * 
1504   * @param serverCorbaClassesHolder   The server corba classesHolder
1505   * @param urlClassLoader             The url class loader
1506   * @param implClass                  The impl class
1507   * @throws ClassGenerationException  The class generation exception
1508   */
1509     private void setWebServiceImpl(
1510         ServerCorbaClassesHolder serverCorbaClassesHolder,
1511         URLClassLoader urlClassLoader,
1512         String implClass) throws ClassGenerationException {
1513 
1514         LOG.debug(">>>>> setWebServiceImpl - begin");
1515         try {
1516             serverCorbaClassesHolder.setWebServiceImpl(
1517                     urlClassLoader.loadClass(implClass));
1518 
1519         } catch (ClassNotFoundException e) {
1520 
1521             Object[] args = new Object[] {
1522                     "setWebServiceImplementation", implClass, urlClassLoader };
1523 
1524             LOG.error("CRB000506_Error_during_method", args, e);
1525             throw new ClassGenerationException(
1526                     "CRB000506_Error_during_method", args, e);
1527         }
1528         LOG.debug("<<<<< setWebServiceImplementation - end");
1529     }
1530 
1531 
1532  /**
1533   * 
1534   * @param serverCorbaClassesHolder   The server corba classes holder
1535   * @param urlClassLoader             The url class loader
1536   * @param poaTie                     The poa tie
1537   * @throws ClassGenerationException  the class generation exception
1538   */
1539   private void setCorbaPOATie(
1540     ServerCorbaClassesHolder serverCorbaClassesHolder,
1541     URLClassLoader urlClassLoader,
1542     String poaTie) throws ClassGenerationException {
1543 
1544     LOG.debug(">>>>> setCorbaPOATie - begin");
1545     try {
1546 
1547       serverCorbaClassesHolder.setCorbaPOATie(
1548               urlClassLoader.loadClass(poaTie));
1549 
1550     } catch (ClassNotFoundException e) {
1551       Object[] args = new Object[] {
1552               "setCorbaPOATie", poaTie, urlClassLoader };
1553 
1554       LOG.error("CRB000506_Error_during_method", args, e);
1555       throw new ClassGenerationException(
1556               "CRB000506_Error_during_method", args, e);
1557     }
1558     LOG.debug("<<<<< setCorbaPOATie - end");
1559   }
1560 
1561   /**
1562    * 
1563    * @param serverCorbaClassesHolder  The server corba classes holder
1564    * @param urlClassLoader            The url class loader
1565    * @param corbaImpl                 The implementation of the corba interface.
1566    * 
1567    * @throws ClassGenerationException  the class generation exception
1568    */
1569    private void setCorbaImpl(
1570      ServerCorbaClassesHolder serverCorbaClassesHolder,
1571      URLClassLoader urlClassLoader,
1572      String corbaImpl) throws ClassGenerationException {
1573 
1574      LOG.debug(">>>>> setCorbaImpl - begin");
1575      try {
1576 
1577        serverCorbaClassesHolder.setCorbaImplClass(
1578                urlClassLoader.loadClass(corbaImpl));
1579 
1580      } catch (ClassNotFoundException e) {
1581        Object[] args = new Object[] {
1582                "setCorbaImpl", corbaImpl, urlClassLoader };
1583 
1584        LOG.error("CRB000506_Error_during_method", args, e);
1585        throw new ClassGenerationException(
1586                "CRB000506_Error_during_method", args, e);
1587      }
1588      LOG.debug("<<<<< setCorbaImpl - end");
1589    }
1590 
1591   /**
1592    * 
1593    * @param serverCorbaClassesHolder   The server corba classes holder
1594    * @param urlClassLoader             The url class loader
1595    * @param operations                 The operations
1596    * @throws ClassGenerationException  The class generation exception
1597    */
1598     private void setCorbaOperations(
1599         ServerCorbaClassesHolder serverCorbaClassesHolder,
1600         URLClassLoader urlClassLoader,
1601         String operations) throws ClassGenerationException {
1602 
1603         LOG.debug(">>>>> setCorbaOperations - begin");
1604         try {
1605             serverCorbaClassesHolder.setCorbaOperations(
1606                     urlClassLoader.loadClass(operations));
1607 
1608         } catch (ClassNotFoundException e) {
1609             Object[] args = new Object[] {
1610                     "setCorbaOperations", operations, urlClassLoader };
1611 
1612             LOG.debug("urlClassLoader.getURLs()="
1613                       + Arrays.asList(urlClassLoader.getURLs()));
1614             LOG.error("CRB000506_Error_during_method", args, e);
1615             throw new ClassGenerationException(
1616                     "CRB000506_Error_during_method", args, e);
1617         }
1618         LOG.debug("<<<<< setCorbaOperations - end");
1619     }
1620 
1621     /**
1622      * The list of names of the jars used in the classpath.
1623      *
1624      * @param    libDirName    The directory where the jars are located.
1625      *
1626      * @return    The list of names of the jars used in the classpath.
1627      *
1628      * @throws    ClassGenerationException
1629      */
1630 //    private List<String> prepareClassPath(String libDirName)
1631 //        throws ClassGenerationException {
1632 //
1633 //        LOG.debug(">>>>> prepareClassPath - begin");
1634 //        List<File> jarFiles
1635 //            = Util.findFilesFromSourceDirectory(libDirName, ".jar");
1636 //
1637 //        List<String> jarFilesName = new ArrayList<String>();
1638 //
1639 //        for (File jarFile:jarFiles) {
1640 //            try {
1641 //                LOG.debug("Adding jar " + jarFile.getCanonicalPath() + " ... ");
1642 //
1643 //                jarFilesName.add(jarFile.getCanonicalPath());
1644 //
1645 //                LOG.debug("... jar " + jarFile.getCanonicalPath() + " added.");
1646 //            } catch (IOException e) {
1647 //                Object[] args = new Object[] { jarFile, e.getMessage() };
1648 //
1649 //                LOG.error("CRB000507_Error_getting_canonicalPath_from_file",
1650 //                          args, e);
1651 //                throw new ClassGenerationException(
1652 //                        "CRB000507_Error_getting_canonicalPath_from_file",
1653 //                        args, e);
1654 //            }
1655 //        }
1656 //
1657 //        LOG.debug("<<<<< prepareClassPath - end");
1658 //        return jarFilesName;
1659 //    }
1660 
1661     /**
1662      * This method copies orb.idl and ir.idl in wsdlDirName.
1663      *
1664      * @param    wsdlDirName        The directory where the files are copied.
1665      *
1666      * @throws    ClassGenerationException  The class generation exception
1667      */
1668     private void copyOrbIrIdl(String wsdlDirName)
1669         throws ClassGenerationException {
1670 
1671         LOG.debug(">>>>> copyOrbIrIdl - begin");
1672 
1673         //add orb.idl and ir.idl
1674         InputStream orbis
1675             =  this.getClass().getClassLoader().getResourceAsStream("orb.idl");
1676 
1677         if (orbis == null) {
1678             LOG.error("CRB000508_Could_not_find_orb.idl_in_path");
1679             throw new ClassGenerationException(
1680                     "CRB000508_Could_not_find_orb.idl_in_path");
1681         } else {
1682             LOG.debug("orbis not null ... orb.idl found");
1683         }
1684 
1685         InputStream iris
1686             = this.getClass().getClassLoader().getResourceAsStream("ir.idl");
1687 
1688         if (iris == null) {
1689             LOG.error("CRB000509_Could_not_find_ir.idl_in_path");
1690             throw new ClassGenerationException(
1691                     "CRB000509_Could_not_find_ir.idl_in_path");
1692         } else {
1693             LOG.debug("iris not null ... ir.idl found");
1694         }
1695 
1696         String orbFileName = wsdlDirName + File.separator + "orb.idl";
1697         String irFileName  = wsdlDirName + File.separator + "ir.idl";
1698 
1699         copyFile(orbis, orbFileName);
1700         copyFile(iris, irFileName);
1701 
1702         LOG.debug("copyFile (orb.idl and ir.idl) to " + wsdlDirName + " ...ok");
1703 
1704         LOG.debug("<<<<< copyOrbIrIdl - end");
1705     }
1706 
1707   /**
1708    * Adds the "remote" charateristics to the PortType class generated.
1709    * The modifications are:
1710    * 1) add the java.rmi.Remote interface to the class
1711    * 2) add the java.rmi.RemoteException to the 'throws' clause of each method.
1712    * 
1713    * @param portTypeClassName  The port type class name
1714    * @param classesDirName     The classes dir name
1715    * @return                   The return
1716    * @throws ClassGenerationException  The class generation exception
1717    */
1718     private String tweakInterfaceClasses(
1719             String portTypeClassName,
1720             String classesDirName) throws ClassGenerationException {
1721 
1722         LOG.debug(">>>>>>>>>> tweakInterfaceClasses - begin");
1723 
1724         LOG.debug("remotizing class: " + portTypeClassName
1725                 + " in dir: " + classesDirName);
1726 
1727         ClassWriter cw = new ClassWriter(true);
1728         ClassVisitor cc = new CheckClassAdapter(cw);
1729         StringWriter sw = new StringWriter();
1730         ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
1731 
1732         RemoteEnhancerAdapter cv = new RemoteEnhancerAdapter(tv,
1733                 getAsFullyQualifiedNameInternalForm(portTypeClassName));
1734 
1735         LOG.debug("new ClassReader - Begin");
1736         ClassReader cr;
1737         try {
1738             cr = new ClassReader(new FileInputStream(getAsFileName(
1739                     classesDirName, portTypeClassName, ".class")));
1740         } catch (IOException e) {
1741             Object[] args = new Object[] { portTypeClassName, classesDirName };
1742 
1743             LOG.error("CRB000510_Could_not_instantiate_class_reader", args, e);
1744             throw new ClassGenerationException(
1745                     "CRB000510_Could_not_instantiate_class_reader", args, e);
1746         }
1747         LOG.debug("new ClassReader - End");
1748 
1749         cr.accept(cv, true);
1750 
1751         LOG.debug("output of tracer during creation of class: "
1752                 + portTypeClassName + "\n" + sw.toString());
1753 
1754         byte [] newBytecode = cw.toByteArray();
1755 
1756         // write class in the right place
1757         String relativeFileName
1758             = cv.getCompleteName().replace('/', File.separatorChar);
1759 
1760         LOG.debug("relativeFileName=" + relativeFileName
1761                 + "; cv.getCompleteName()=" + cv.getCompleteName());
1762 
1763         Util.saveAsJavaClass(classesDirName + File.separator + relativeFileName
1764                 + ".class", newBytecode);
1765 
1766         String remoteClassName = cv.getCompleteName().replace('/', '.');
1767 
1768         LOG.debug("<<<<<<<<<< tweakInterfaceClasses - end:" + remoteClassName);
1769         return remoteClassName;
1770     }
1771 
1772 
1773 
1774     // ========================
1775     //          Utility Methods
1776     // ========================
1777 
1778 /**
1779  * @param sourceFileName             The source file name
1780  * @param destFileName               The dest file name
1781  * @throws ClassGenerationException  The class generation exception
1782  */
1783     private void copyFile(String sourceFileName,String destFileName)
1784         throws ClassGenerationException {
1785 
1786         LOG.debug(">>>>>>>>>> copyFile(String, String) - begin");
1787 
1788         LOG.debug("copying: " + sourceFileName + " to: " + destFileName);
1789 
1790         FileInputStream is;
1791         try {
1792             is = new FileInputStream(sourceFileName);
1793         } catch (FileNotFoundException e) {
1794             Object[] args = new Object[] { sourceFileName, e.getMessage() };
1795 
1796             LOG.error("CRB000511_Error_opening", args, e);
1797             throw new ClassGenerationException(
1798                     "CRB000511_Error_opening", args, e);
1799         }
1800 
1801         copyFile(is, destFileName);
1802         LOG.debug("<<<<<<<<<< copyFile(String, String) - end");
1803     }
1804 
1805  /**
1806   * @param sourceInputStream          The source input stream
1807   * @param destFileName               The dest file name
1808   * @throws ClassGenerationException  The class generation exception
1809   */
1810     private void copyFile(InputStream sourceInputStream, String destFileName)
1811         throws ClassGenerationException {
1812 
1813         LOG.debug(">>>>>>>>>> copyFile(InputStream, String) - begin");
1814 
1815         FileOutputStream fos;
1816 
1817         LOG.debug("copying: " + sourceInputStream + " to: " + destFileName);
1818         try {
1819 
1820             fos = new FileOutputStream(new File(destFileName));
1821 
1822         } catch (FileNotFoundException e) {
1823             Object[] args = new Object[] { destFileName, e.getMessage() };
1824 
1825             LOG.error("CRB000512_Error_creating", args, e);
1826             throw new ClassGenerationException(
1827                     "CRB000512_Error_creating", args, e);
1828         }
1829 
1830         LOG.debug("FileUtil.copyInputStream");
1831 
1832         try {
1833             Util.copyInputStream(sourceInputStream, fos);
1834         } catch (IOException e) {
1835             Object[] args = new Object[] {
1836                     sourceInputStream, destFileName, e.getMessage() };
1837 
1838             LOG.error("CRB000513_Error_copying_input_stream", args, e);
1839             throw new ClassGenerationException(
1840                     "CRB000513_Error_copying_input_stream", args, e);
1841         }
1842 
1843         LOG.debug("<<<<<<<<<< copyFile(InputStream, String) - end");
1844     }
1845 
1846 //    /**
1847 //     * Generetes Java source from IDL files (TIE model).
1848 //     *
1849 //     * @param    sourceDirName  The source dir name
1850 //     * @param    idlFilename  The idl file name
1851 //     * @param    wsdlDirName  The wsdl dir name
1852 //     * @param    destIdlFileName  The dest idl file name
1853 //     *
1854 //     */
1855 //    private void idl2javaTieModel(String sourceDirName, String idlFilename,
1856 //        String wsdlDirName, String destIdlFileName) {
1857 //
1858 //        LOG.debug(">>>>>>>>>> idl2java - begin");
1859 //
1860 //        LOG.debug("\n workdir: "         + sourceDirName
1861 //                + ";\n idlfilename: "    + idlFilename
1862 //                + ";\n wsdlDirName:"     + wsdlDirName
1863 //                + ";\n destIdlFileName:" + destIdlFileName);
1864 //
1865 //        /* Run the IDL-to-Java compiler, idlj, TWICE on the IDL file
1866 //         * to create stubs and skeletons.
1867 //         * This step assumes that you have included the path to the java/bin
1868 //         * directory in your path.
1869 //         *
1870 //         * idlj -fall  Hello.idl
1871 //         * idlj -fallTie Hello.idl
1872 //         *
1873 //         * You must use the -fall option with the idlj compiler
1874 //         * to generate both client and server-side bindings.
1875 //         * This command line will generate the default server-side bindings,
1876 //         * which assumes the POA programming model.
1877 //         *
1878 //         * The -fallTie option generates another file, HelloPOATie,
1879 //         * which is used to create a Tie.
1880 //         */
1881 //
1882 //        /* OPTIONS:
1883 //         *  -fall       To generate both client and server-side bindings.
1884 //         *     -td    <dir>   Use <dir> for the output instead of the current dir.
1885 //         *  -i <dir>    The current dir is scanned for included files.
1886 //         *              This option adds another directory.
1887 //         *  -emitAll    Emit all types, including those found in #include files.
1888 //         *  -v          Verbose.
1889 //         */
1890 //
1891 //        String [] optionsFALL = new String[] { "-fall", "-td", sourceDirName,
1892 //          "-i", wsdlDirName, "-emitAll", destIdlFileName };
1893 //
1894 //        if (LOG.isDebugEnabled()) {
1895 //          LOG.debug("Compile. 1) -fall");
1896 //          //LOG.debug("If debug is enable you see a warning message of IDLJ:"
1897 //          //        + "'Error reading Messages File.'");
1898 //
1899 //          // whe debug is enable we use the option 'verbose'.
1900 //          optionsFALL = new String[] { "-fall", "-td", sourceDirName, "-v",
1901 //            "-i", wsdlDirName, "-emitAll", destIdlFileName };
1902 //        }
1903 //
1904 //
1905 //        com.sun.tools.corba.se.idl.toJavaPortable.Compile.main(optionsFALL);
1906 //
1907 //
1908 //        String [] optionsFallTie = new String[] { "-fallTIE", "-td",
1909 //          sourceDirName, "-i", wsdlDirName, "-emitAll", destIdlFileName };
1910 //
1911 //        if (LOG.isDebugEnabled()) {
1912 //            LOG.debug("Compile. 2) -fallTIE");
1913 //            //LOG.debug("If debug is enable you see a warning message of IDLJ:"
1914 //            //        + "'Error reading Messages File.'");
1915 //
1916 //            // whe debug is enable we use the option 'verbose'.
1917 //            optionsFallTie = new String[] {"-fallTIE", "-td", sourceDirName,
1918 //              "-v", "-i", wsdlDirName, "-emitAll", destIdlFileName };
1919 //          }
1920 //
1921 //        com.sun.tools.corba.se.idl.toJavaPortable.Compile.main(optionsFallTie);
1922 //
1923 //        LOG.debug("<<<<<<<<<< idl2java - end");
1924 //    }
1925 
1926 /**
1927  * @return  The return
1928  * @throws ClassGenerationException  The class generation exception
1929  */
1930     private FileSystemManager getFileSystemManager()
1931         throws ClassGenerationException {
1932 
1933         try {
1934             return VFS.getManager();
1935         } catch (FileSystemException e) {
1936             Object[] args = new Object[] { e.getMessage() };
1937 
1938             LOG.error("CRB000514_Error_inizializing_virtual_filesystem",
1939                       args, e);
1940             throw new ClassGenerationException(
1941                     "CRB000514_Error_inizializing_virtual_filesystem", args, e);
1942         }
1943     }
1944 
1945 /**
1946  * @param classesDirName  The classes dir name 
1947  * @return  The return
1948  * @throws ClassGenerationException  The class generation exception
1949  */
1950     private URLClassLoader getURLClassLoader(String classesDirName)
1951         throws ClassGenerationException {
1952 
1953         LOG.debug(">>>>>>>>>> getURLClassLoader - begin");
1954 
1955         URLClassLoader urlClassLoader = null;
1956         String protocol = null;
1957         try {
1958 
1959           if (System.getProperty("os.name").indexOf("Win") >=0) {
1960               protocol = "file:///";
1961           } else {
1962               protocol = "file://";
1963           }
1964 
1965           urlClassLoader = new URLClassLoader(
1966                 new URL[] { new URL(protocol + classesDirName + "/") },
1967                   this.getClass().getClassLoader());
1968 
1969           LOG.debug("url classloader: "
1970                 + Arrays.asList(urlClassLoader.getURLs()));
1971         } catch (MalformedURLException e) {
1972             Object[] args = new Object[] { protocol + classesDirName + "/" };
1973 
1974             LOG.error("CRB000515_Could_not_instantiate_url_class_loader",
1975                       args, e);
1976             throw new ClassGenerationException(
1977                     "CRB000515_Could_not_instantiate_url_class_loader", args,
1978                     e);
1979         }
1980 
1981         LOG.debug("<<<<<<<<<< getURLClassLoader - end");
1982         return urlClassLoader;
1983     }
1984 
1985 
1986 
1987     /**
1988      * Copy a WSDL file in workdir with the name 'service.wsdl'.
1989      *
1990      * @param    workdir            Where to copy the wsdl.
1991      * @param    wsdlStringUrl    Where the wsdl is located.
1992      *
1993      * @return    wsdl dir (as file).
1994      *
1995      * @throws    ClassGenerationException  The class generation exception
1996      */
1997     private File copyWsdlTo(String workdir, String wsdlStringUrl)
1998         throws ClassGenerationException {
1999 
2000         LOG.debug(">>>>>>>>>> copyWsdlTo - begin");
2001 
2002         LOG.debug("workdir=" + workdir + "; wsdlStringUrl=" + wsdlStringUrl);
2003 
2004         File workdirFile = new File(workdir);
2005         FileSystemManager fsManager = getFileSystemManager();
2006 
2007         FileObject wsdlFile;
2008         try {
2009             wsdlFile = fsManager.resolveFile(wsdlStringUrl);
2010         } catch (FileSystemException e) {
2011             Object[] args = new Object[] { wsdlStringUrl, e.getMessage() };
2012 
2013             LOG.error("CRB000516_Error_resolving_file", args, e);
2014             throw new ClassGenerationException(
2015                     "CRB000516_Error_resolving_file", args, e);
2016         }
2017 
2018         LOG.debug("wsdl location resolved");
2019         
2020         InputStream wsdlInputStream;
2021         try {
2022             wsdlInputStream = wsdlFile.getContent().getInputStream();
2023         } catch (IOException e) {
2024             Object[] args = new Object[] { wsdlFile, e.getMessage() };
2025 
2026             LOG.error("CRB000517_Error_opening_url_inputstream", args, e);
2027             throw new ClassGenerationException(
2028                     "CRB000517_Error_opening_url_inputstream", args, e);
2029         }
2030 
2031         LOG.debug("wsdl content extracted");
2032 
2033         File wsdlDirFile;
2034         String wsdlDirName;
2035         try {
2036             wsdlDirFile = Util.createUniqueDirectory(workdirFile, "wsdl");
2037             wsdlDirName = wsdlDirFile.getCanonicalPath();
2038         } catch (IOException e) {
2039             Object[] args = new Object[] { e.getMessage() };
2040 
2041             LOG.error("CRB000518_Error_creating_dir_for_wsdl", args, e);
2042             throw new ClassGenerationException(
2043                     "CRB000518_Error_creating_dir_for_wsdl", args, e);
2044         }
2045 
2046         LOG.debug("wsdl dir created:" + wsdlDirName);
2047 
2048         String wsdlFileName =  getWsdlFileName(wsdlDirName);
2049 
2050         copyFile(wsdlInputStream, wsdlFileName);
2051 
2052         LOG.debug("wsdl copied: " + wsdlFileName);
2053         LOG.debug("<<<<<<<<<< copyWsdlTo - end");
2054         return wsdlDirFile;
2055     }
2056 
2057    /**
2058     * @param wsdlDirName  The wsdl dir name
2059     * @return  The return
2060     */
2061     private String getWsdlFileName(String wsdlDirName) {
2062         return wsdlDirName + File.separator + "service.wsdl";
2063     }
2064 
2065     /**
2066      * This method create a new directory.
2067      *
2068      * @param    basedir        Where the new directory must be created.
2069      * @param    newdir        The name of the new directory.
2070      *
2071      * @return    The canonical path of the new directory.
2072      *
2073      * @throws    ClassGenerationException  The classgeneration exception
2074      */
2075     private String mkdir(File basedir, String newdir)
2076         throws ClassGenerationException {
2077 
2078         LOG.debug(">>>>> mkdir - begin");
2079 
2080             File sourceDir = new File(basedir, newdir);
2081             Util.buildDirectory(sourceDir);
2082             String sourceDirName;
2083         try {
2084             sourceDirName = sourceDir.getCanonicalPath();
2085         } catch (IOException e) {
2086             Object[] args = new Object[] { sourceDir, e.getMessage() };
2087 
2088             LOG.error("CRB000519_Error_getting_canonical_path", args, e);
2089             throw new ClassGenerationException(
2090                     "CRB000519_Error_getting_canonical_path", args, e);
2091         }
2092 
2093         LOG.debug("<<<<< mkdir - end. newdir=" + sourceDirName);
2094         return sourceDirName;
2095     }
2096 
2097     /**
2098      * This method is used to generate the java source code that maps a WSDL.
2099      *
2100      * @param    wsdlDirName        Where the wsdl is located.
2101      * @param    sourceDirName    Where the source will be generate.
2102      *
2103      * @return   The information extracted from the WSDL file.
2104      *
2105      * @throws   ClassGenerationException  The class generation exception
2106      */
2107     private WsdlInformation wsdlToJava(String wsdlDirName, String sourceDirName, List<String> jars)
2108         throws ClassGenerationException {
2109 
2110         LOG.debug(">>>>> wsdlToJava - begin");
2111         
2112         String wsdlFileName = getWsdlFileName(wsdlDirName);
2113 
2114         ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); 
2115         
2116         WsdlInformation wsdlInformation = null;
2117 
2118         try {
2119             // Gets the factory classloader to make the PlugiTools to correctly load the ObjectFactory class
2120             org.apache.cxf.tools.plugin.ObjectFactory factory = new org.apache.cxf.tools.plugin.ObjectFactory();
2121             ClassLoader factoryClassLoader = factory.getClass().getClassLoader();
2122             Thread.currentThread().setContextClassLoader(factoryClassLoader);       
2123 
2124             WSDLToJava gen = new WSDLToJava();
2125 
2126             String[] w2jArgs = new String[]{"-d", sourceDirName, wsdlFileName};                                       
2127             gen.setArguments(w2jArgs);        
2128             wsdlInformation = extractWsdlInformation(wsdlFileName);
2129 
2130             LOG.debug("wsdlDirName="       + wsdlDirName
2131                       + "; wsdlFileName="    + wsdlFileName
2132                       + "; OutputDirectory=" + sourceDirName);
2133 
2134             gen.run(new ToolContext());                                   
2135 
2136         } catch (Exception e) {
2137         	e.printStackTrace();
2138             Object[] args = new Object[] { wsdlFileName, e.getMessage() };
2139 
2140             LOG.error("CRB000520_Error_generating_source_file", args, e);
2141             throw new ClassGenerationException(
2142                     "CRB000520_Error_generating_source_file", args, e);
2143         } finally {
2144             // Sets back the previous classloader
2145             Thread.currentThread().setContextClassLoader(oldClassLoader);    
2146         }
2147 
2148         LOG.debug("<<<<< wsdlToJava - end");
2149         return wsdlInformation;
2150     }
2151 
2152     /**
2153      * This method extract the PortTypes present in the wsdl.
2154      *
2155      * @param    wsdlFileName    The absolute file name of the wsdl.
2156      *
2157      * @return   The object that contains the information of the WSDL.
2158      *
2159      * @throws   ClassGenerationException  The class generation exception
2160      */
2161     private WsdlInformation extractWsdlInformation(String wsdlFileName)
2162         throws ClassGenerationException {
2163         LOG.debug(">>>>> extractWsdlInformation - begin");
2164 
2165         WsdlInformation wi = new WsdlInformation();
2166 
2167         try {
2168             
2169             // Gets the Service model from the service
2170             CXFUtils.setupBus();
2171             WSDLServiceBuilder b = new WSDLServiceBuilder(CXFUtils.getBus());
2172             
2173             // Gets the WSDL Definition
2174             WSDLFactory wsdlFactory = WSDLFactory.newInstance();
2175             final WSDLReader reader =  wsdlFactory.newWSDLReader();
2176             reader.setFeature(Constants.FEATURE_VERBOSE, false);
2177             reader.setFeature(Constants.FEATURE_IMPORT_DOCUMENTS, true);
2178           
2179             final Definition def = reader.readWSDL(wsdlFileName);
2180             
2181             List<ServiceInfo> serviceInfo = b.buildServices(def);
2182                                    
2183             for (Object o : serviceInfo) {
2184                 ServiceInfo sInfo = (ServiceInfo) o;
2185                 
2186                 // Gets the porttype (interface) name
2187                 QName pt = sInfo.getInterface().getName();
2188                 wi.getPortTypeList().add(pt);
2189                 LOG.debug("PortType[" + pt + "] in WsdlFile=" + wsdlFileName);
2190 
2191                 wi.getServiceAndPortType().put(sInfo.getName(), pt);
2192 
2193                 wi = findOperationByMEP(sInfo, pt, wi);
2194             }
2195 
2196         } catch (Exception e) {
2197             LOG.error("CRB000521_Extracting_PortTypes_error", e);
2198             throw new ClassGenerationException(
2199                     "CRB000521_Extracting_PortTypes_error", null, e);
2200         }
2201 
2202         LOG.debug("<<<< extractWsdlInformation - end");
2203         return wi;
2204     }
2205 
2206     /**
2207      * This method extracts asychronous and synchronous operation and store
2208      * them in the WsdlInformation object.
2209      *
2210      * @param   service   The service to inspect.
2211      * @param   portType  The portType associated to the operations.
2212      * @param   wi        The WsdlInformation used.
2213      *
2214      * @return  The WsdlInformation updated.
2215      */
2216     protected WsdlInformation findOperationByMEP(ServiceInfo serviceInfo,
2217       QName portType, WsdlInformation wi) {
2218 
2219       if (wi == null) {
2220         wi = new WsdlInformation();
2221       }
2222       if (portType == null) {
2223         LOG.debug("No operations for a nillable PortType!");
2224         return wi;
2225       }
2226 
2227       // init
2228       List<QName> asyncList = new ArrayList<QName>();
2229       List<QName> syncList = new ArrayList<QName>();
2230       wi.getAsynchOperationMap().put(portType, asyncList);
2231       wi.getSynchOperationMap().put(portType, syncList);
2232 
2233       if (serviceInfo == null) {
2234         LOG.debug("No operations for a nillable service!");
2235         return wi;
2236       }
2237       
2238       Iterator opIterator
2239         = serviceInfo.getInterface().getOperations().iterator();
2240 
2241       while (opIterator.hasNext()) {
2242         OperationInfo op = (OperationInfo) opIterator.next();
2243 
2244         /* isAsync doesn't work as I expected ... as usual :-(
2245          *
2246          * So if the operation has no output I suppose is oneway
2247          * 
2248          */
2249         LOG.debug("OperationInfo.isAsync:" + op.isOneWay()
2250                 + "; OperationInfo.hasInput()=" + op.hasInput()
2251                 + "; OperationInfo.hasOutput()=" + op.hasOutput());
2252 
2253         if (! op.hasOutput()) {
2254           LOG.debug("Asynchronous Operation; operationName=" + op.getName());
2255 
2256           wi.getAsynchOperationMap().get(portType).add(op.getName());
2257         } else {
2258           LOG.debug("Synchronous Operation; operationName=" + op.getName());
2259 
2260           wi.getSynchOperationMap().get(portType).add(op.getName());
2261         }
2262       }
2263 
2264       return wi;
2265     }
2266 
2267 
2268     /**
2269      * This method extract the service name for the PortType from the WSDL.
2270      *
2271      * @param    wsdlDirName    The wsdl dir name
2272      * @param    portType       The port type
2273      *
2274      * @return   The service name
2275      *
2276      * @throws   ClassGenerationException  The class generation exception 
2277      */
2278     private QName extractServiceNameFromPortType(String wsdlDirName, QName portType)
2279         throws ClassGenerationException {
2280         LOG.debug(">>>>> extractPortTypes - begin");
2281 
2282         String wsdlFileName = getWsdlFileName(wsdlDirName);
2283         try {
2284 
2285             // Gets the Service model from the service
2286             WSDLServiceBuilder b = new WSDLServiceBuilder(CXFUtils.getBus());
2287             
2288             // Gets the WSDL Definition
2289             WSDLFactory wsdlFactory = WSDLFactory.newInstance();
2290             final WSDLReader reader = ((WSDLFactoryImpl) wsdlFactory).newWSDLReader();
2291             reader.setFeature(Constants.FEATURE_VERBOSE, false);
2292             reader.setFeature(Constants.FEATURE_IMPORT_DOCUMENTS, true);
2293                                     
2294             final Definition def = reader.readWSDL(wsdlFileName);
2295             
2296             List<ServiceInfo> serviceInfo = b.buildServices(def);
2297             
2298             for (Object o : serviceInfo) {
2299                 QName pt = ((ServiceInfo) o).getInterface().getName();
2300                 if (pt.equals(portType)) {
2301                     QName serviceName = ((ServiceInfo) o).getName();
2302                     LOG.debug("Service[" + serviceName + "] found in WsdlFile=" + wsdlFileName + " for portType:" + portType);
2303                     return serviceName;
2304                 }
2305             }
2306             // IF no service is found, throws an exception
2307             LOG.error("CRB000542_Error_during_service_name_lookup", String.valueOf(portType));
2308             throw new ClassGenerationException("CRB000542_Error_during_service_name_lookup", new Object[]{String.valueOf(portType)});
2309 
2310         } catch (Exception e) {
2311             LOG.error("CRB000542_Error_during_service_name_lookup", e);
2312             throw new ClassGenerationException(
2313                     "CRB000542_Error_during_service_name_lookup", null, e);
2314         }
2315     }
2316 
2317 
2318     /**
2319      * 
2320      * @param basedir   The base dir
2321      * @param javaName  The java name
2322      * @param ext  The ext
2323      * @return  The return
2324      */
2325     private String getAsFileName(String basedir, String javaName, String ext) {
2326         // FIXME null
2327         char sep = File.separator.charAt(0);
2328         basedir = basedir.replace('\\', sep).replace('/', sep);
2329 
2330         return basedir + sep + javaName.replace('.', sep) + ext;
2331     }
2332 
2333   /**
2334    * 
2335    * @param javaName  The java name
2336    * @return  The return
2337    */
2338     private String getAsFullyQualifiedNameInternalForm(String javaName) {
2339         // FIXME null
2340         return javaName.replace('.', '/');
2341     }
2342     
2343     
2344     /**
2345      * Add <code>java.lang.Exception</code> as Superclass.
2346      * The exception classes generated from the WSDL does not extends
2347      * <code>java.lang.Exception</code>.
2348      * 
2349      * Code taken from the JBi4Ejb project
2350      * 
2351      * @param exceptions
2352      *          The exceptions to transform
2353      * @param classesDirName
2354      *          Where the classes are
2355      * 
2356      * @throws ClassGenerationException
2357      *          If some problem occurs
2358      */
2359     private void addExceptionSuperclass(List<String> exceptions, String classesDirName) 
2360             throws ClassGenerationException {
2361         
2362         for (int i = 0; i < exceptions.size(); i++) {
2363             String exception = exceptions.get(i);
2364             LOG.debug("Adding Exception superclass to exception: " + exception);
2365             
2366             ClassWriter  cw = new ClassWriter(true); // visitMaxs
2367             ClassVisitor cc = new CheckClassAdapter(cw);
2368             StringWriter sw = new StringWriter();
2369             ClassVisitor tv = new TraceClassVisitor(cc, new PrintWriter(sw));
2370             
2371             AddExceptionSuperclass cv = new AddExceptionSuperclass(tv);
2372             
2373             ClassReader cr;
2374             try {
2375                 cr = new ClassReader(new FileInputStream(getAsFileName(
2376                         classesDirName, exception, ".class")));
2377             } catch (IOException e) {
2378             	String msg=MESSAGES.getString("CRB000557_Failure_generating_ClassReader_in_addExceptionSuperclass", 
2379             			new Object[] {e.getMessage()});
2380                 LOG.error(msg,e);
2381                 throw new ClassGenerationException(msg,e);
2382 
2383             }
2384             cr.accept(cv, true);
2385             byte[] newBytecode = cw.toByteArray();
2386 
2387             // Save the class bytecode
2388             String relativeFileName = exception.replace('.', File.separatorChar);
2389             Util.saveAsJavaClass(classesDirName + File.separator +
2390                     relativeFileName + ".class", newBytecode);
2391 
2392         }
2393     }
2394     
2395 	/**
2396 	 * Returns true if the string parameter is null or empty.
2397 	 * @param str
2398 	 *            The string to be checked
2399 	 *             
2400 	 * @return The return
2401 	 */
2402     private boolean isEmpty(String str) {
2403     	return ((str == null) || (str.trim().length() <= 0));
2404     }
2405  
2406 	/**
2407 	 * Returns true if the jbiServiceDescriptor object contains details that point to a valid idl file.
2408 	 * @param jbiServiceDescriptor
2409 	 *            The Object that contains details about IDL (file name and directory)
2410 	 *             
2411 	 * @return The return
2412 	 */
2413     private boolean isIdlIncluded(JbiServiceDescriptor jbiServiceDescriptor)
2414 			throws ClassGenerationException {
2415 		boolean result = false;
2416 		
2417 		if (jbiServiceDescriptor == null || 
2418 			isEmpty(jbiServiceDescriptor.getIdlFileName()) || 
2419 			isEmpty(jbiServiceDescriptor.getIdlFileNameDirectory())) {
2420 			return false;
2421 		}
2422 
2423 		String filepath = jbiServiceDescriptor.getIdlFileNameDirectory()
2424 				+ File.separator + jbiServiceDescriptor.getIdlFileName();
2425 
2426 		try {
2427 			File idlFile = new File(filepath);
2428 			if (idlFile.exists()) {
2429 				String idl = HelperFileUtil.readFileAsString(idlFile).trim();
2430 				result = (! isEmpty(idl));
2431 			}
2432 		} catch (Exception e) {
2433 			Object[] args = new Object[] { filepath, e.getMessage() };
2434 			LOG.error("CRB000512_Error_creating", args, e);
2435 			throw new ClassGenerationException("CRB000512_Error_creating",
2436 					args, e);
2437 		}
2438 		return result;
2439 	}
2440 }