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.exception.WSDLGenerationException;
15  import it.imolinfo.jbi4corba.jbi.JbiServiceDescriptor;
16  import it.imolinfo.jbi4corba.jbi.Messages;
17  import it.imolinfo.jbi4corba.jbi.cxf.CXFUtils;
18  import it.imolinfo.jbi4corba.jbi.cxf.Jbi4CorbaIdlPreprocessor;
19  import it.imolinfo.jbi4corba.jbi.wsdl.Jbi4CorbaAddress;
20  import it.imolinfo.jbi4corba.jbi.wsdl.Jbi4CorbaBinding;
21  import it.imolinfo.jbi4corba.jbi.wsdl.Jbi4CorbaExtension;
22  import it.imolinfo.jbi4corba.schema.DefinitionAndSchema;
23  import it.imolinfo.jbi4corba.schema.SchemaUtil;
24  import it.imolinfo.jbi4corba.utils.HelperFileUtil;
25  import it.imolinfo.jbi4corba.utils.HelperIDLJUtil;
26  import it.imolinfo.jbi4corba.utils.HelperStringUtils;
27  import it.imolinfo.jbi4corba.utils.IdlFileDataHolder;
28  import it.imolinfo.jbi4corba.webservice.descriptor.ProviderServiceDescriptor;
29  import it.imolinfo.jbi4corba.webservice.runtime.ProviderServiceCreator;
30  
31  import java.io.ByteArrayOutputStream;
32  import java.io.File;
33  import java.io.FileNotFoundException;
34  import java.io.IOException;
35  import java.net.URISyntaxException;
36  import java.net.URL;
37  import java.util.ArrayList;
38  import java.util.HashMap;
39  import java.util.Iterator;
40  import java.util.LinkedList;
41  import java.util.List;
42  import java.util.Map;
43  
44  import javax.wsdl.Binding;
45  import javax.wsdl.BindingFault;
46  import javax.wsdl.BindingInput;
47  import javax.wsdl.BindingOperation;
48  import javax.wsdl.BindingOutput;
49  import javax.wsdl.Definition;
50  import javax.wsdl.Operation;
51  import javax.wsdl.Port;
52  import javax.wsdl.Service;
53  import javax.wsdl.WSDLException;
54  import javax.wsdl.extensions.ExtensionRegistry;
55  import javax.wsdl.extensions.schema.Schema;
56  import javax.wsdl.factory.WSDLFactory;
57  import javax.wsdl.xml.WSDLReader;
58  import javax.xml.namespace.QName;
59  import javax.xml.parsers.DocumentBuilder;
60  import javax.xml.parsers.DocumentBuilderFactory;
61  import javax.xml.parsers.ParserConfigurationException;
62  import javax.xml.transform.TransformerException;
63  import javax.xml.xpath.XPathConstants;
64  
65  import org.apache.cxf.helpers.XMLUtils;
66  import org.apache.cxf.helpers.XPathUtils;
67  import org.apache.cxf.service.model.ServiceInfo;
68  import org.apache.cxf.tools.corba.idlpreprocessor.DefaultIncludeResolver;
69  import org.apache.cxf.tools.corba.idlpreprocessor.DefineState;
70  import org.apache.cxf.tools.corba.idlpreprocessor.IncludeResolver;
71  import org.apache.cxf.wsdl.WSDLConstants;
72  import org.w3c.dom.Document;
73  import org.w3c.dom.Element;
74  import org.w3c.dom.NamedNodeMap;
75  import org.w3c.dom.NodeList;
76  import org.xml.sax.InputSource;
77  import org.xml.sax.SAXException;
78  
79  import com.ibm.wsdl.Constants;
80  import com.ibm.wsdl.extensions.schema.SchemaConstants;
81  import it.imolinfo.jbi4corba.jbi.wsdl.Jbi4CorbaIDLEntry;
82  import java.util.Set;
83  
84  /**
85   * Class to generate WSDL file starting from an IDL file. Usually this class is
86   * used by NetBeans plugin.
87   * 
88   * 
89   * @author <a href="mailto:mcimatti@imolinfo.it">Marco Cimatti</a>
90   * @author <a href="mailto:lacquaviva@imolinfo.it">Luca Acquaviva</a>
91   */
92  public final class WSDLGenerator {
93  
94  	/**
95  	 * The WS-ADDRESSING NAMESPACE
96  	 **/
97  	private final String WSADDNS = "http://www.w3.org/2006/03/addressing/ws-addr.xsd";
98  	
99  	private final String XSDWSNS = "http://www.w3.org/2005/08/addressing";
100         
101         private final String PATHSEPARATOR="/";
102 
103 	private List<org.apache.cxf.service.Service> services = new ArrayList<org.apache.cxf.service.Service>();
104 	/**
105 	 * The only instance created for this class, according to <i>singleton</i>
106 	 * pattern.
107 	 */
108 	private static final WSDLGenerator THE_INSTANCE = new WSDLGenerator();
109 	/**
110 	 * Logger.
111 	 */
112 	private static final Logger LOG = LoggerFactory
113 			.getLogger(WSDLGenerator.class);
114 	
115 	private static final Messages MESSAGES = Messages
116 			.getMessages(WSDLGenerator.class);
117 
118 	/**
119 	 * Creates an instance of this class.
120 	 */
121 	private WSDLGenerator() {
122 	}
123 
124 	/**
125 	 * Gets an instance of this class.
126 	 * 
127 	 * @return an instance of this class, ready to use.
128 	 */
129 	public static WSDLGenerator getWSDLGenerator() {
130 		return THE_INSTANCE;
131 	}
132 
133 	/**
134 	 * Creates a WSDL file starting from an IDL file. The generated WSDL
135 	 * contains only one binding, related to the JBI4Corba component.
136 	 * 
137 	 * @param desc
138 	 *            the descriptor incapsulating all required informations to
139 	 *            generate a complete WSDL. Must be not <code>null</code>.
140 	 * @return The WSDL definition
141 	 * @throws ClassGenerationException
142 	 *             if an error occurs during java class generation.
143 	 * @throws IOException
144 	 *             if an I/O error occurs while reading from or writing to a
145 	 *             file.
146 	 * @throws WSDLException
147 	 *             if an error occurs manipulating the WSDL to adjust its
148 	 *             content. CRB-80 New Method added generateWSDLListfromIDL
149 	 */
150 	@Deprecated
151 	public Definition generateWSDLfromIDL(final File idlFile,
152 			final WSDLDescriptor desc) throws ClassGenerationException,
153 			IOException, WSDLException, WSDLGenerationException,
154 			Jbi4CorbaException {
155 
156 		ArrayList<WSDLDescriptor> descList = new ArrayList<WSDLDescriptor>();
157 		descList.add(desc);
158 
159 		return generateWSDLListfromIDL(idlFile, descList).get(0);
160 
161 	}
162 
163 	/**
164 	 * Extract all the #include information from the original idl file
165 	 * 
166 	 * Added by
167 	 * 
168 	 * @author <a href="mailto:jussi.nummelin@nsn.com">Jussi Nummelin</a>
169 	 * 
170 	 * @param original
171 	 *            The original IDL file
172 	 * @param resolvedIDL
173 	 *            Temporary IDL file to write to
174 	 * 
175 	 * @throws IOException
176 	 *             Thrown in case of problems resolving the includes.
177 	 */
178 	private Jbi4CorbaIdlPreprocessor resolveIncludes(File original)
179 			throws IOException, FileNotFoundException, Jbi4CorbaException {
180 
181 		try {
182 
183 			URL idlUrl = original.toURI().toURL();
184 
185 			final File includeDir = original.getAbsoluteFile().getParentFile();
186 
187 			LOG.debug("Starting to resolve includes");
188 
189 			IncludeResolver includeResolver = new DefaultIncludeResolver(
190 					includeDir);
191 			DefineState defineState = new DefineState(
192 					new HashMap<String, String>());
193 
194 			Jbi4CorbaIdlPreprocessor preprocessor = new Jbi4CorbaIdlPreprocessor(
195 					idlUrl, ".", includeResolver, defineState);
196                         //For each url open the file and comment the line #include                 
197                         
198                         
199                         return preprocessor;
200                         
201 		} finally {
202 			LOG.debug("All includes resolved succesfully");
203 		}
204                
205 	}
206         
207    /**
208     * Change #Include status in the original idl
209     * it is used for comment #include <orb.idl> and #include <ir.idl> in the 
210     * classes generation phase
211     * @param idlUrls the set of file url 
212     * @param status the status see {@link HelperFileUtil} for details
213     * 
214     * */     
215    private void changeNotNeededIncludeStatus(Set<URL> idlURLs,int status) throws FileNotFoundException, IOException, Jbi4CorbaException{
216                         
217                         for(URL url: idlURLs){
218                             try {
219                                 HelperFileUtil.changeIDLIncludeStaus(url, status);
220                             } catch (URISyntaxException ex) {
221                                
222                                String msg = MESSAGES
223 					.getString("CRB000577_Error_On_idl_preprocessing");
224                                LOG.error(msg, ex);
225                                throw new Jbi4CorbaException(msg);
226                             }
227                         }  
228    }
229         
230               
231 	/**
232 	 * Creates a WSDL file starting from an IDL file. The generated WSDL
233 	 * contains only one binding, related to the JBI4Corba component.
234 	 * 
235 	 * @param desc
236 	 *            the descriptor incapsulating all required informations to
237 	 *            generate a complete WSDL. Must be not <code>null</code>.
238 	 * @return The List of WSDL definition
239 	 * @throws ClassGenerationException
240 	 *             if an error occurs during java class generation.
241 	 * @throws IOException
242 	 *             if an I/O error occurs while reading from or writing to a
243 	 *             file.
244 	 * @throws WSDLException
245 	 *             if an error occurs manipulating the WSDL to adjust its
246 	 *             content.
247 	 * 
248 	 *             CRB-80 Modify the endpoint name generation the portType is
249 	 *             the endpointname
250 	 * 
251 	 */
252 	public List<Definition> generateWSDLListfromIDL(final File idlFile,
253 			final ArrayList<WSDLDescriptor> descList)
254 			throws ClassGenerationException, IOException, WSDLException,
255 			WSDLGenerationException, Jbi4CorbaException {
256                         
257                 services = new ArrayList<org.apache.cxf.service.Service>();        
258 		// Resolve all includes
259 		
260                 Set<String> includePath;
261                 Set<URL>    idlTodisableImportUrl;
262                
263 		try {
264                     //Idl File is the root element file
265                          Jbi4CorbaIdlPreprocessor processor=resolveIncludes(idlFile);
266                          includePath =processor.getIncludesPath();
267                          idlTodisableImportUrl=processor.getIdlURL();
268 		} catch (IOException ex) {
269 			String msg = MESSAGES
270 					.getString("CRB000575_Error_Resolving_Include");
271 			throw new WSDLGenerationException(msg, ex);
272 		}
273                 
274                 
275 	
276 		// If the file no contains interfaces it throws an exception
277 		if (idlInterfacesCounter(idlFile) == 0) {
278 			String msg = MESSAGES
279 					.getString("CRB000576_Error_No_interface_found_in_the_idl");
280 			throw new Jbi4CorbaException(msg);
281 		}
282 	
283 		WSDLFactory factory = WSDLFactory.newInstance();
284 	
285 		WSDLReader reader = factory.newWSDLReader();
286 	
287                 changeNotNeededIncludeStatus(idlTodisableImportUrl,HelperFileUtil.DISABLE );
288                 try{
289 		List<String> stringWsdlList = createWSDLfromIDLFile(idlFile,
290 				descList);
291                          
292 		LinkedList<Definition> defList = new LinkedList<Definition>();
293 	
294 		for (String stringWsdl : stringWsdlList) {
295 	
296 			// The Position of ws-addr.xsd
297 			// Change the xsd location only for the wsdl generation
298 			// *****************************************************
299 			// Generate the ws-address.xsd and use it
300 			// Generate the file in the target directory
301 			// *****************************************************
302 
303 			
304 			if (stringWsdl.lastIndexOf(WSADDNS) != -1) {
305 	
306 				URL schemaWsAddrUrl = this.getClass().getResource("/xsdSchema/ws-addr.xsd");				
307 
308 				stringWsdl = stringWsdl.replaceAll(WSADDNS, schemaWsAddrUrl.toString());
309 				
310 			}
311 				 
312 			if (LOG.isDebugEnabled()) {
313 				LOG.debug(stringWsdl);
314 			}
315 	
316 			ExtensionRegistry registry = factory
317 					.newPopulatedExtensionRegistry();
318 			
319 			Definition def;
320 			Service service;
321 			Port port;
322 			Jbi4CorbaAddress address;
323 			Binding binding;
324 	
325 			WSDLDescriptor desc =null;
326 	
327 			// Reads the Definition from the String (passing through the DOM
328 			// parser)
329 			Document wsdlDoc = parseWsdlDocument(stringWsdl);
330 			LOG.debug("CRB000573_wsdlDoc_getDocumentURI", new Object[] { wsdlDoc
331 					.getDocumentURI() });
332 	
333 			// if there are many interfaces in different module's the wsdl of
334 			// the most
335 			// internal interface include the wsdl of the external interface.
336 			// TODO bug to fix multimodule interface
337 			// Disable the process of imported files for fix bug
338 			reader.setFeature("javax.wsdl.importDocuments", false);
339 			
340 			def = reader.readWSDL(wsdlDoc.getDocumentURI(), wsdlDoc);
341 			
342 			def.setExtensionRegistry(registry);
343 			def.addNamespace(Jbi4CorbaExtension.DEFAULT_PREFIX,
344 					Jbi4CorbaExtension.NS_URI_JBI4CORBA);
345 
346             
347 
348                         for (int id = 0; id < descList.size(); id++) {
349 	
350 				if (def.getQName().equals(new QName(descList.get(id).getNamespace(),descList.get(id).getEndpointName()))) {
351 					desc = descList.get(id);
352 					break;
353 				}
354 	
355 			}
356 			
357 			QName oldBindingName = new QName(desc.getNamespace(), desc
358 					.getEndpointName()
359 					+ "SoapBinding");
360 			Jbi4CorbaBinding corbaBinding;
361 
362 			// Removes the old service, which has the same name as the new one
363 			// we're
364 			// going to create
365 			def.removeService(new QName(desc.getNamespace(), desc
366 					.getCorbaServiceName()));
367 	
368 			// Adds a new Service with our estension
369 			service = def.createService();
370 			service.setQName(new QName(desc.getNamespace(), desc
371 					.getEndpointName()));
372 			def.addService(service);
373 	
374 			// Adds the port
375 			port = def.createPort();
376 			port.setName(desc.getEndpointName() + "CorbaPort");
377 			service.addPort(port);
378 	
379 			// Adds the extended address
380 			address = new Jbi4CorbaAddress();
381 			address.setElementType(Jbi4CorbaExtension.Q_ELEM_JBI4CORBA_ADDRESS);
382 			address.setName(desc.getCorbaServiceName());
383 			address.setLocalizationType(desc.getLocalizationType());
384 			address.setOrbProperties(desc.getOrbProperties());
385                         address.setPeristent(desc.isPersistentConsumer());
386 			port.addExtensibilityElement(address);
387 	
388 			// Adds the binding
389 			binding = def.createBinding();
390 			binding.setUndefined(false);
391 			binding.setQName(new QName(desc.getNamespace(), desc
392 					.getEndpointName()
393 					+ "CorbaBinding"));
394 			binding.setPortType(def.getPortType(new QName(desc.getNamespace(),
395 					desc.getEndpointName())));
396 			port.setBinding(binding);
397 			def.addBinding(binding);
398 				
399 			for (Object o : def.getBinding(oldBindingName)
400 					.getBindingOperations()) {
401 				BindingOperation bo = (BindingOperation) o;
402 				Operation op = bo.getOperation();
403 				BindingInput in = bo.getBindingInput();
404 				BindingOutput out = bo.getBindingOutput();
405 	
406 				// Clones the <wsdl:operation> element to remove inner elements
407 				// contained in the "wsdlsoap" namespace
408 				BindingOperation newBo = def.createBindingOperation();
409 				Operation newOp = def.createOperation();
410 				BindingInput newIn = def.createBindingInput();
411 				BindingOutput newOut = def.createBindingOutput();
412 	
413 				newBo.setName(bo.getName());
414 				newOp.setName(op.getName());
415 				newIn.setName(in.getName());
416 				if (out != null) {
417 					newOut.setName(out.getName());
418 					newBo.setBindingOutput(newOut);
419 				}
420 				newBo.setOperation(newOp);
421 				newBo.setBindingInput(newIn);
422 	
423 				for (Object obj : bo.getBindingFaults().values()) {
424 					BindingFault fault = (BindingFault) obj;
425 					BindingFault newFault = def.createBindingFault();
426 	
427 					newFault.setName(fault.getName());
428 					newBo.addBindingFault(newFault);
429 				}
430 	
431 				binding.addBindingOperation(newBo);
432 			}
433 			def.removeBinding(oldBindingName);
434 	
435 			// Adds the extended binding
436 			corbaBinding = new Jbi4CorbaBinding();
437 			corbaBinding.setElementType(Jbi4CorbaExtension.Q_ELEM_JBI4CORBA_BINDING);
438                         
439                         /*****************************************************************/
440                         //Insert the Root idl File
441                             Jbi4CorbaIDLEntry jbi4CorbaIDLEntry=new Jbi4CorbaIDLEntry();
442                             jbi4CorbaIDLEntry.setIdlFilename(idlFile.getName());
443                             jbi4CorbaIDLEntry.setRoot(true);
444                           
445                             jbi4CorbaIDLEntry.setIDL(HelperFileUtil.readFileAsString(idlFile));
446                             corbaBinding.getJbi4CorbaDLEntryList().add(jbi4CorbaIDLEntry);
447                         
448                         /*****************************************************************/  
449                         //Adding all include idl to the wsdl    
450                         for(String idlToInclude : includePath ){
451                             int lastSeparator=idlToInclude.lastIndexOf(PATHSEPARATOR);
452                             String fileName=idlToInclude;
453                             String relativePath="";
454                             if(lastSeparator>0){
455                                 relativePath=PATHSEPARATOR+idlToInclude.substring(0,lastSeparator)+PATHSEPARATOR;   
456                                 fileName=idlToInclude.substring(lastSeparator+1);
457                             }
458                             
459                             jbi4CorbaIDLEntry=new Jbi4CorbaIDLEntry();
460                             jbi4CorbaIDLEntry.setIdlFilename(fileName);
461                             jbi4CorbaIDLEntry.setRoot(false);
462                             jbi4CorbaIDLEntry.setRelativePath(relativePath);
463                             //Add IDL
464                             File idlF=new File(idlFile.getParent()+File.separator+idlToInclude);
465                         
466                             jbi4CorbaIDLEntry.setIDL(HelperFileUtil.readFileAsString(idlF));
467                             
468                             corbaBinding.getJbi4CorbaDLEntryList().add(jbi4CorbaIDLEntry);
469                         
470                         }
471 			binding.addExtensibilityElement(corbaBinding);
472 			
473                         int length = 0;
474 			if (def.getTypes() != null) {
475 				length = def.getTypes().getExtensibilityElements().size();
476 			}
477 			LOG.debug(">>>>>>>> XSDSchema's number: " + length);
478 	
479 			// get all schema in the WSDL and add the import if is needed
480 			for (int i = 0; i < length; i++) {
481 				Schema xmlschema = (Schema) def.getTypes()
482 						.getExtensibilityElements().get(i);
483 				Map attribute = getNameSpaceList(xmlschema);
484 				// Add the import in the wsdl
485 				addRequiredSchemaImports(xmlschema, attribute);
486 			}
487 	
488 			defList.add(def);
489 	
490 		}
491 	
492                
493 		return defList;
494                 }finally{
495                  changeNotNeededIncludeStatus(idlTodisableImportUrl,HelperFileUtil.ENABLE );      
496                 
497                 }
498                 
499 	}
500 
501 	/**
502 	 * Added by
503 	 * 
504 	 * @author <a href="mailto:lacquaviva@imolinfo.it">Luca Acquaviva</a>
505 	 *         Creates a WSDL file starting from an IDL, using the default JBI
506 	 *         binding.
507 	 * 
508 	 * @param idl
509 	 *            the IDL file to read from. Must be not <code>null</code>.
510 	 * @param desc
511 	 *            the descriptor incapsulating all required informations to
512 	 *            generate a complete WSDL. Must be not <code>null</code>.
513 	 * @return the created WSDL file or <code>null</code> if temporary
514 	 *         directories could not be created.
515 	 * @throws IOException
516 	 *             if an I/O error occurs while reading from or writing to a
517 	 *             file.
518 	 * @throws ClassGenerationException
519 	 *             if an error occurs during java class generation.
520 	 */
521 	private List<String> createWSDLfromIDLFile(final File idl,
522 			final List<WSDLDescriptor> descList) throws IOException,
523 			ClassGenerationException, Jbi4CorbaException {
524 
525 		List<JbiServiceDescriptor> jbiDescList = new LinkedList<JbiServiceDescriptor>();
526 
527 		CodeGenerationProperties codeGenProp = new CodeGenerationProperties();
528 		codeGenProp.setValueTypeImplementationWithToStringAndEquals(false);
529 
530 		ProviderServiceClassesGenerator generator = new ProviderServiceClassesGenerator(
531 				codeGenProp);
532 
533 		File tempDir = createTempDir();
534 
535 		if (tempDir == null) {
536 			return null;
537 		}
538 
539 		ArrayList<String> cxfWsdlList = new ArrayList<String>();
540 
541 		List<String> portTypes = new ArrayList<String>();
542 
543 		for (WSDLDescriptor desc : descList) {
544 			JbiServiceDescriptor jbiDesc = new JbiServiceDescriptor();
545 			jbiDesc.setIdlFileNameDirectory(idl.getParentFile()
546 					.getAbsolutePath());
547 			jbiDesc.setIdlFileName(idl.getName());
548 			jbiDesc.setServiceNameSpace(desc.getNamespace());
549 			
550                         jbiDesc.setPortTypeName(new QName(desc.getEndpointName()));
551                         
552 
553 			portTypes.add(desc.getEndpointName());
554 
555 			jbiDescList.add(jbiDesc);
556 
557 		}
558 
559 		try {
560 
561 			List<ClientCorbaClassesHolder> classes = generator
562 					.generateProviderServiceClasses(jbiDescList, tempDir
563 							.getAbsolutePath(), (String) null, portTypes);
564 
565 			// May be one to multiple classes CRB-80
566 			// if the idl file contains more than one interface there are many
567 			// corbaClasses
568 
569 			for (ClientCorbaClassesHolder corbaClasses : classes) {
570 				WSDLDescriptor desc = null;
571 				
572 				String 	className=corbaClasses
573 				.getOperationsClass().getName().substring(corbaClasses
574 						.getOperationsClass().getName().lastIndexOf(".")+1,corbaClasses
575 						.getOperationsClass().getName().length()-10);
576 			
577 				String namespace = corbaClasses.getOperationsClass().getName()
578                                                 .substring(0,corbaClasses.getOperationsClass().getName().length()-10);
579                  
580 				// If there is only one interfaces it takes the first descriptor
581 				
582 				if (classes.size() > 1) {
583 					desc = getWsdlDescByIntName(className,namespace, descList);
584 				}else{
585                  desc = descList.get(0);
586                 }
587 				// if descriptor is not null than it generate the wsdl
588 				if (desc != null) {
589 
590 					ProviderServiceDescriptor serviceDesc = new ProviderServiceDescriptor();
591 					org.apache.cxf.service.Service service;
592 
593 					QName interfaceName = new QName(desc.getNamespace(), desc
594 							.getEndpointName());
595 
596 					serviceDesc.setServiceInterface(corbaClasses
597 							.getOperationsClass());
598 					serviceDesc.setCorbaHelperClass(corbaClasses
599 							.getHelperClass());
600 					serviceDesc.setServiceName(desc.getCorbaServiceName());
601 					serviceDesc.setServiceNameSpace(desc.getNamespace());
602 					String cxfWsdl = null;
603 					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
604 
605 					try {
606 
607 						service = new ProviderServiceCreator().createService(
608 								serviceDesc, interfaceName);
609 
610 						CXFUtils.writeDefinitionOnOutputStream(service,
611 								outputStream);
612 						services.add(service);
613 
614 					} catch (WSDLException e) {
615 						String msg = MESSAGES
616 								.getString("CRB000574_Error_in_WSDL_generation");
617 						LOG.error(msg, e);
618 						throw new ClassGenerationException(msg, e);
619 
620 					} catch (Jbi4CorbaException e) {
621 						String msg = MESSAGES
622 								.getString("CRB000574_Error_in_WSDL_generation");
623 						LOG.error(msg, e);
624 						throw new ClassGenerationException(msg, e);
625 					}
626 
627 					cxfWsdl = outputStream.toString();
628                    
629 					cxfWsdlList.add(cxfWsdl);
630 				}
631 
632 			}
633 
634 			return cxfWsdlList;
635 
636 		} finally {
637 			deleteDirectory(tempDir);
638 		}
639 	}
640 
641 	/**
642 	 * This method return the correct descriptor when there are many interfaces
643 	 * It return the descriptor based on the matching ofthe name of class an an
644 	 * Endpoint Name
645 	 * 
646 	 * @param List
647 	 *            <WSDLDescriptor>
648 	 * @param String
649 	 *            name the interface name
650 	 * @return WSDLDescriptor
651 	 */
652 	private WSDLDescriptor getWsdlDescByIntName(final String name,final String namespace,
653 			final List<WSDLDescriptor> descList) {
654 
655 		for (WSDLDescriptor desc : descList) {
656 			
657 			if (desc.getEndpointName().equals(name) && desc.getNamespace().equals("http://"+namespace)) {
658 				return desc;
659 			}
660 		}
661 		//Added To Run OldTest
662 		for (WSDLDescriptor desc : descList) {
663 			
664 			if (desc.getEndpointName().equals(name)) {
665 				return desc;
666 			}
667 		}
668 
669 		
670 		return null;
671 	}
672 
673 	/**
674 	 * This method should be used in sequence with the method
675 	 * generateWSDLListfromIDL it accepts the definition generated list from
676 	 * method <code>generateWSDLListfromIDL</code> 1) Remove the content of tag
677 	 * <code>schema</code> and add the import schema file generated; 2) Create
678 	 * xsd schema for each xmlSchema in the WSDL. 3)
679 	 * 
680 	 * @param definition
681 	 *            Definition WSDlL
682 	 * @param service
683 	 *            service's name
684 	 * @throws java.io.IOException
685 	 * @throws javax.xml.parsers.ParserConfigurationException
686 	 * @return definition without schema anda separated schema
687 	 */
688 	public DefinitionAndSchema createRemoveXSD(List<Definition> definition)
689 			throws IOException, ParserConfigurationException,
690 			TransformerException {
691 
692 		List<Schema> schemas = new ArrayList<Schema>();
693 		DefinitionAndSchema defandschema = new DefinitionAndSchema();
694 		int index = 0;
695 		for (Definition def : definition) {
696          
697 			ServiceInfo serviceInfo = services.get(index).getServiceInfos()
698 					.get(0);
699 			List<Schema> wrapperList = SchemaUtil.getSchemaWrapperList(
700 					serviceInfo, def);
701 
702 			int length = def.getTypes().getExtensibilityElements().size();
703 
704 			LOG.debug(">>>>>>>> XSDSchema's number: " + length);
705 
706 			// get all schema in the WSDL
707 			for (int i = 0; i < length; i++) {
708 				Schema xmlschema = (Schema) def.getTypes()
709 						.getExtensibilityElements().get(i);
710 				
711 				if (!schemas.contains(xmlschema)) {
712 					schemas.add(xmlschema);
713 					
714 				}
715 			}
716                         // Remove the wrapper from the schemalist for mantain this inline in
717 			// the wsdl
718 			for (int ii = 0; ii < wrapperList.size(); ii++) {
719 				if (schemas.contains(wrapperList.get(ii))) {
720 					schemas.remove(wrapperList.get(ii));
721                                                                              
722 				}
723 			}
724 						 
725 			for (int i = 0; i < schemas.size(); i++) {
726 
727 				// Remove all the schema from the wsdl
728 				// remove tags schema from definition
729 				def.getTypes().getExtensibilityElements().removeAll(schemas);
730 				// Remove the wrapper
731 				def.getTypes().getExtensibilityElements()
732 						.removeAll(wrapperList);
733 
734 				
735 			}
736 			// MARCO: If there's no schema, this logic shouldn't be executed 
737 			if (schemas.size() != 0) {
738 				Schema wrapper = null;
739 				if (wrapperList.size() > 0) {
740 
741 					wrapper = wrapperList.get(0);
742 
743 					// Change import type in wrapper
744 
745 					Element element = wrapper.getElement();
746 					String schemaPrefix = element.getPrefix();
747 
748 					NodeList nodes = element.getElementsByTagName(schemaPrefix
749 							+ ":" + Constants.ELEM_IMPORT);
750 					for (int ii = 0; ii < nodes.getLength(); ii++) {
751 						Element el = (Element) nodes.item(ii);
752 						String namespace = el
753 								.getAttribute(Constants.ATTR_NAMESPACE);
754 						String schemaLocation = SchemaUtil.generateFileNameXSD(
755 								namespace, "TypeDef");
756 						// Added for manage ENDPOINT-REFERENCE W3C
757 						if (namespace.equals(XSDWSNS)) {
758 							defandschema.setContainsW3c(true);
759 							schemaLocation = "ws-addr.xsd";
760 						}
761 
762 						el.setAttribute(SchemaConstants.ATTR_SCHEMA_LOCATION,
763 								schemaLocation);
764 					}
765 
766 					// Add the wrapper
767 					if (wrapper != null) {
768 
769 						def.getTypes().getExtensibilityElements().add(wrapper);
770 					}
771 				}
772 			//}
773 			}
774 		
775 			
776 			index++;
777 		}
778 
779 		defandschema.setDefinition(definition);
780 		defandschema.setSchemas(schemas);
781 		return defandschema;
782 
783 	}
784 
785 	/**
786 	 * 
787 	 * Returns the numbers of Interfaces from an IDL
788 	 * 
789 	 * @param idl
790 	 *            the IDL file to read from. Must be not <code>null</code>.
791 	 * @return
792 	 * @throws IOException
793 	 *             if an I/O error occurs while reading file.
794 	 */
795 	public int idlInterfacesCounter(final File idlFile) throws IOException,
796 			Jbi4CorbaException {
797 		
798 		return idlInterfacesNames(idlFile).size();
799 
800 	}
801 
802 	/**
803 	 * 
804 	 * Returns the Interface's name from an IDL
805 	 * 
806 	 * @param idl
807 	 *            the IDL file to read from. Must be not <code>null</code>.
808 	 * @return Interfaces Names
809 	 * @throws IOException
810 	 *             if an I/O error occurs while reading file.
811 	 */
812 	public List<String> idlInterfacesNames(final File idlFile)
813 			throws IOException, Jbi4CorbaException {
814 
815 		CodeGenerationProperties codeGenProp = new CodeGenerationProperties();
816 		codeGenProp.setValueTypeImplementationWithToStringAndEquals(false);
817 		List<String> names = new ArrayList<String>();
818 
819 		File tempDir = createTempDir();
820 
821 		if (tempDir == null) {
822 			return null;
823 		}
824                  Set<URL> idlUrl= resolveIncludes(idlFile).getIdlURL();
825                 //Comment not needed import
826                 changeNotNeededIncludeStatus(idlUrl,HelperFileUtil.DISABLE );
827 		HelperIDLJUtil.idlj(tempDir.getAbsolutePath(), idlFile.getParent(), idlFile
828 				.getCanonicalPath());
829                 changeNotNeededIncludeStatus(idlUrl,HelperFileUtil.ENABLE );
830 		List<String> javaSources = Util.findJavaSources(tempDir
831 				.getCanonicalPath());
832 		for (String canFilename : javaSources) {
833 			if (canFilename.endsWith("Operations.java")) {
834 				String name=HelperStringUtils.ExtractString(canFilename, String
835 						.valueOf(File.separator), "Operations.java");
836 				                                
837                         names.add(name);
838 			}
839 		}
840 
841 		deleteDirectory(tempDir);
842 
843 		return names;
844 	}
845 
846 	/**
847 	 * 
848 	 * Returns The names' and namespace's from an idl
849 	 * 
850 	 * @param idl
851 	 *            the IDL file to read from. Must be not <code>null</code>.
852 	 * @return Interfaces Names
853 	 * @throws IOException
854 	 *             if an I/O error occurs while reading file.
855 	 */
856 	public List<IdlFileDataHolder> getIdlFileData(final File idlFile)
857 			throws IOException, Jbi4CorbaException {
858 
859 		
860 		CodeGenerationProperties codeGenProp = new CodeGenerationProperties();
861 		codeGenProp.setValueTypeImplementationWithToStringAndEquals(false);
862 
863 		File tempDir = createTempDir();
864 
865 		if (tempDir == null) {
866 			return null;
867 		}
868                 Set<URL> idlUrl= resolveIncludes(idlFile).getIdlURL();
869                 //Comment not needed import
870                 changeNotNeededIncludeStatus(idlUrl,HelperFileUtil.DISABLE );
871 		HelperIDLJUtil.idlj(tempDir.getAbsolutePath(), idlFile.getParent(), idlFile
872 				.getCanonicalPath());
873                 //DeComment not needed import
874                 changeNotNeededIncludeStatus(idlUrl,HelperFileUtil.ENABLE );
875 		List<IdlFileDataHolder> holderList = new ArrayList<IdlFileDataHolder>();
876 		IdlFileDataHolder holder;
877 
878 		List<String> javaSources = Util.findJavaSources(tempDir
879 				.getCanonicalPath());
880 		for (String canFilename : javaSources) {
881 			if (canFilename.endsWith("Operations.java")) {				
882 				String name = HelperStringUtils.ExtractString(canFilename,
883 						String.valueOf(File.separator), "Operations.java");
884 				
885 			
886 				if(!javaSources.contains(canFilename.substring(0,canFilename.length()-15)+"OperationsOperations.java")){
887 					
888 					int lastIndex = canFilename.lastIndexOf(File.separator);
889 					int startIndex = tempDir.getCanonicalPath().length() + 1;
890 
891 					String nameSpace = "default";
892 					if (lastIndex - startIndex > 0) {
893 						nameSpace = canFilename.substring(startIndex, lastIndex);
894 					}
895 
896 					nameSpace = Util.replaceSeparatorWithDot(nameSpace);
897 					nameSpace = "http://" + nameSpace + "." + name;
898 					holder = new IdlFileDataHolder(name, nameSpace);
899 					holderList.add(holder);
900 					}
901 				}
902 
903 		}
904 
905 		deleteDirectory(tempDir);
906 
907 		return holderList;
908 	}
909 
910 	/**
911 	 * Creates a temporary directory.
912 	 * 
913 	 * @return the created directory or <code>null</code> if the creation has
914 	 *         failed even though a file has been created.
915 	 * @throws IOException
916 	 *             if a file could not be created.
917 	 */
918 	private static File createTempDir() throws IOException {
919 		File f = File.createTempFile("IDL2WSDLWIZARD_", null);
920 
921 		/*
922 		 * java.io.File API can create only temporary files: delete the created
923 		 * file and make a directory with the same name
924 		 */
925 		if (!f.delete()) {
926 			return null;
927 		}
928 		if (!f.mkdir()) {
929 			return null;
930 		}
931 		return f;
932 	}
933 
934 	/**
935 	 * Tries to delete a directory, even though it's not empty.
936 	 * 
937 	 * @param directory
938 	 *            the directory to delete. Must be not <code>null</code>.
939 	 */
940 	private static void deleteDirectory(final File directory) {
941 		File[] files = directory.listFiles();
942 
943 		if (files != null) {
944 			for (File f : files) {
945 				if (f.isDirectory()) {
946 					deleteDirectory(f);
947 				} else {
948 					f.delete();
949 				}
950 			}
951 		}
952 		directory.delete();
953 	}
954 
955 	/**
956 	 * Parses the wsdl document into a <code>Document</code>
957 	 * 
958 	 * @param wsdlDoc
959 	 * 
960 	 * @return the document
961 	 * 
962 	 * @throws Jbi4CorbaException
963 	 */
964 	private Document parseWsdlDocument(String wsdlDoc)
965 			throws WSDLGenerationException {
966 
967 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
968 		DocumentBuilder mBuilder;
969 		Document wrappedDoc = null;
970 
971 		try {
972 			factory.setNamespaceAware(true);
973 			mBuilder = factory.newDocumentBuilder();
974 			
975 			// Bug Multimodule Interface
976 			wrappedDoc = mBuilder.parse(new InputSource(
977 					new java.io.StringReader(wsdlDoc)));
978 
979 		} catch (ParserConfigurationException ex) {
980 			Object[] args = new Object[] { ex.getMessage() };
981 			LOG.error("CRB000554_Error_during_wsdl_parsing", args, ex);
982 			throw new WSDLGenerationException(
983 					"CRB000554_Error_during_wsdl_parsing", args, ex);
984 		} catch (SAXException ex) {
985 			Object[] args = new Object[] { ex.getMessage() };
986 			LOG.error("CRB000554_Error_during_wsdl_parsing", args, ex);
987 			throw new WSDLGenerationException(
988 					"CRB000554_Error_during_wsdl_parsing", args, ex);
989 		} catch (IOException ex) {
990 			Object[] args = new Object[] { ex.getMessage() };
991 			LOG.error("CRB000554_Error_during_wsdl_parsing", args, ex);
992 			throw new WSDLGenerationException(
993 					"CRB000554_Error_during_wsdl_parsing", args, ex);
994 		}
995 		LOG.debug("wrappedDoc.class" + wrappedDoc.getClass());
996 		return wrappedDoc;
997 	}
998 
999 	/**
1000 	 * Add schema imports if is needed.
1001 	 * 
1002 	 * @param schemaElement
1003 	 * @param attribute
1004 	 */
1005 	protected void addRequiredSchemaImports(Schema schema, Map attribute) {
1006 
1007 		LOG.debug("addRequiredSchemaImports - BEGIN");
1008 		Element schemaElement = schema.getElement();
1009 		String schemaNamespace = schemaElement
1010 				.getAttribute(Constants.ATTR_TARGET_NAMESPACE);
1011 
1012 		Map<String, String> queryPrefixMap = new HashMap<String, String>();
1013 		queryPrefixMap.put("xs", WSDLConstants.NP_SCHEMA_XSD);
1014 		XPathUtils xpu = new XPathUtils(queryPrefixMap);
1015 
1016 		Iterator iterator = attribute.keySet().iterator();
1017 		do {
1018 			String prefix = (String) iterator.next();
1019 			String namespace = (String) attribute.get(prefix);
1020 
1021 			if (!namespace.equals(schemaNamespace)
1022 					&& !namespace.equals(WSDLConstants.NP_SCHEMA_XSD)
1023 					&& !xpu.isExist(
1024 							"xs:import[@namespace='" + namespace + "']",
1025 							schemaElement, XPathConstants.NODE)
1026 					&& !xpu.isExist("xsd:import[@namespace='" + namespace
1027 							+ "']", schemaElement, XPathConstants.NODE)
1028 					&& !namespace.equals(WSDLConstants.NS_SCHEMA_XSD)
1029 					&& !namespace.equals(XSDWSNS)
1030 					&& schema.getImports().get(namespace) == null
1031 
1032 			) {
1033 
1034 				LOG.debug("Add Import for namespace: " + namespace);
1035 				Element importElement = XMLUtils.createElementNS(schemaElement
1036 						.getOwnerDocument(), new QName(schemaElement
1037 						.getPrefix()
1038 						+ ":import"));
1039 
1040 				importElement.setAttribute("namespace", namespace);
1041 				schemaElement.insertBefore(importElement, schemaElement
1042 						.getFirstChild());
1043 
1044 				schema.getImports().put("namespace", namespace);
1045 			}
1046 		} while (iterator.hasNext());
1047 		LOG.debug("addRequiredSchemaImports - END");
1048 	}
1049 
1050 	/**
1051 	 * Get namespace declarated in the schema tag.
1052 	 * 
1053 	 * @param schema
1054 	 * @return
1055 	 */
1056 	private Map getNameSpaceList(Schema schema) {
1057 
1058 		Element el = schema.getElement();
1059 		NamedNodeMap mapAttr = el.getAttributes();
1060 		Map result = new HashMap();
1061 
1062 		for (int i = 0; i < mapAttr.getLength(); i++) {
1063 
1064 			String nsURI = mapAttr.item(i).getNamespaceURI();
1065 			if (nsURI != null && nsURI.equals(Constants.NS_URI_XMLNS)) {
1066 				String prefix = mapAttr.item(i).getLocalName();
1067 				String value = mapAttr.item(i).getNodeValue();
1068 				LOG.debug("Found namespace: " + mapAttr.item(i));
1069 
1070 				result.put(prefix, value);
1071 			}
1072 		}
1073 		// LOG.debug("Map : " + result);
1074 		return result;
1075 	}
1076 }