KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > core > JaxWsUtils


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.websvc.core;
21
22 import com.sun.source.tree.AnnotationTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.ExpressionTree;
25 import com.sun.source.tree.MethodTree;
26 import com.sun.source.tree.ModifiersTree;
27 import com.sun.source.tree.TypeParameterTree;
28 import com.sun.source.tree.VariableTree;
29 import java.io.IOException JavaDoc;
30 import java.net.URI JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Map JavaDoc;
36 import javax.lang.model.element.Modifier;
37 import javax.lang.model.element.TypeElement;
38 import org.netbeans.api.java.classpath.ClassPath;
39 import org.netbeans.api.java.project.JavaProjectConstants;
40 import org.netbeans.api.java.source.CancellableTask;
41 import org.netbeans.api.java.source.JavaSource;
42 import org.netbeans.api.java.source.JavaSource.Phase;
43 import org.netbeans.api.java.source.TreeMaker;
44 import org.netbeans.api.java.source.WorkingCopy;
45 import org.netbeans.api.project.Project;
46 import org.netbeans.api.project.ant.AntArtifact;
47 import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
48 import org.netbeans.modules.j2ee.common.Util;
49 import org.netbeans.modules.j2ee.common.source.GenerationUtils;
50 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
51 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
52 import org.netbeans.modules.web.api.webmodule.WebModule;
53 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlModel;
54 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlOperation;
55 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlParameter;
56 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlPort;
57 import org.netbeans.modules.websvc.api.jaxws.wsdlmodel.WsdlService;
58 import org.netbeans.modules.websvc.core.jaxws.bindings.model.BindingsModel;
59 import org.netbeans.modules.websvc.core.jaxws.bindings.model.BindingsModelFactory;
60 import org.netbeans.modules.websvc.core.jaxws.bindings.model.GlobalBindings;
61 import org.netbeans.modules.websvc.jaxws.api.JAXWSSupport;
62 import org.netbeans.modules.xml.xam.ModelSource;
63 import org.netbeans.spi.java.project.classpath.ProjectClassPathExtender;
64 import org.netbeans.spi.project.ant.AntArtifactProvider;
65 import org.openide.ErrorManager;
66 import org.openide.NotifyDescriptor;
67 import org.openide.WizardDescriptor;
68 import org.openide.cookies.EditorCookie;
69 import org.openide.filesystems.FileObject;
70 import org.openide.loaders.DataObject;
71 import org.openide.util.NbBundle;
72 import org.openide.util.RequestProcessor;
73 import java.util.Iterator JavaDoc;
74
75 /**
76  *
77  * @author mkuchtiak
78  */

79 public class JaxWsUtils {
80     
81     private static int projectType;
82     
83     protected static final int JSE_PROJECT_TYPE = 0;
84     protected static final int WEB_PROJECT_TYPE = 1;
85     protected static final int EJB_PROJECT_TYPE = 2;
86     
87     private static boolean jwsdpSupported = false;
88     private static boolean jsr109Supported = false;
89     
90     /** Creates a new instance of JaxWsUtils */
91     public JaxWsUtils() {
92     }
93     
94     /** This method is called from Refresh Service action
95      */

96     public static void generateJaxWsImplementationClass(Project project, FileObject targetFolder, String JavaDoc targetName, WsdlModel wsdlModel, org.netbeans.modules.websvc.api.jaxws.project.config.Service service) throws Exception JavaDoc {
97         WsdlService wsdlService = wsdlModel.getServiceByName(service.getServiceName());
98         WsdlPort wsdlPort = null;
99         if (wsdlService != null)
100             wsdlPort = wsdlService.getPortByName(service.getPortName());
101         if (wsdlService!=null && wsdlPort!=null) {
102             String JavaDoc serviceID = service.getName();
103             if(wsdlPort.isProvider()){
104                 generateProviderImplClass(project, targetFolder, targetName, wsdlService, wsdlPort, serviceID);
105             }else{
106                 generateJaxWsImplClass(project, targetFolder, targetName, null, wsdlService, wsdlPort, false, serviceID);
107             }
108         }
109     }
110     
111     /** This method is called from Create Web Service from WSDL wizard
112      */

113     public static void generateJaxWsImplementationClass(Project project, FileObject targetFolder, String JavaDoc targetName, URL JavaDoc wsdlURL, WsdlService service, WsdlPort port) throws Exception JavaDoc {
114             generateJaxWsImplClass(project, targetFolder, targetName, wsdlURL, service, port, true, null);
115     }
116     
117     /** This method is called from Create Web Service from WSDL wizard
118      */

119     public static void generateJaxWsArtifacts(Project project, FileObject targetFolder, String JavaDoc targetName, URL JavaDoc wsdlURL, String JavaDoc service, String JavaDoc port) throws Exception JavaDoc {
120         initProjectInfo(project);
121         JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
122         String JavaDoc artifactsPckg = "service."+targetName.toLowerCase(); //NOI18N
123
ClassPath classPath = ClassPath.getClassPath(targetFolder, ClassPath.SOURCE);
124         String JavaDoc serviceImplPath = classPath.getResourceName(targetFolder, '.', false);
125         jaxWsSupport.addService(targetName, serviceImplPath+"."+targetName, wsdlURL.toExternalForm(), service, port, artifactsPckg, jsr109Supported && Util.isJavaEE5orHigher(project));
126     }
127     
128     
129     public static void generateProviderImplClass(Project project, FileObject targetFolder,
130             String JavaDoc targetName, WsdlService service, WsdlPort port, String JavaDoc serviceID) throws Exception JavaDoc{
131 // Retouche
132
// initProjectInfo(project);
133
// JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
134
// String wsdlLocation = jaxWsSupport.getWsdlLocation(serviceID);
135
// JavaClass javaClass = null;
136
// JavaModel.getJavaRepository().beginTrans(true);
137
//
138
// try{
139
// javaClass = JMIGenerationUtil.createClass(targetFolder, targetName);
140
// //Initially, Provider<Source> will be implemented. The user can then change the Provider type if he/she wishes
141
// JMIUtils.addInterface(javaClass, "javax.xml.ws.Provider<Source>"); //NOI18N
142
//
143
// if (projectType == EJB_PROJECT_TYPE) {//EJB project
144
// Annotation statelessAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.ejb.Stateless", Collections.EMPTY_LIST); //NOI18N
145
// javaClass.getAnnotations().add(statelessAnnotation);
146
// }
147
//
148
// //Initially, set mode to PAYLOAD. The user can then change if he/she wishes
149
// AttributeValue serviceModeValue = JMIGenerationUtil.createAttributeValue(javaClass, "value", "javax.xml.ws.Service.Mode", "PAYLOAD"); //NOI18N
150
// ArrayList attrList = new ArrayList();
151
// attrList.add(serviceModeValue);
152
// Annotation serviceModeAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.xml.ws.ServiceMode", attrList); //NOI18N
153
// javaClass.getAnnotations().add(serviceModeAnnotation);
154
//
155
// AttributeValue wsdlLocationValue = JMIGenerationUtil.createAttributeValue(javaClass, "wsdlLocation", wsdlLocation );
156
// AttributeValue serviceNameAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "serviceName", service.getName()); //NOI18N
157
// AttributeValue targetNamespaceAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "targetNamespace", port.getNamespaceURI()); //NOI18N
158
// AttributeValue portNameAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "portName", port.getName()); //NOI18N
159
// attrList = new ArrayList();
160
// attrList.add(wsdlLocationValue);
161
// attrList.add(serviceNameAttibuteValue);
162
// attrList.add(targetNamespaceAttibuteValue);
163
// attrList.add(portNameAttibuteValue);
164
// Annotation serviceProviderAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.xml.ws.WebServiceProvider", attrList); //NOI18N
165
// javaClass.getAnnotations().add(serviceProviderAnnotation);
166
// String returnType = "javax.xml.transform.Source"; //NOI18N
167
// String operationName = "invoke"; //NOI18N
168
// Method op = JMIGenerationUtil.createMethod(javaClass, operationName, Modifier.PUBLIC, returnType);
169
// Parameter param = JMIGenerationUtil.createParameter(javaClass, "source", returnType); //NOI18N
170
// op.getParameters().add(param);
171
// op.setBodyText("//TODO implement this method\nreturn null;"); //NOI18N
172
// javaClass.getFeatures().add(op);
173
// }finally{
174
// JavaModel.getJavaRepository().endTrans();
175
// }
176
//
177
// FileObject fo = JavaModel.getFileObject(javaClass.getResource());
178
// //open in the editor
179
// DataObject dobj = DataObject.find(fo);
180
// openFileInEditor(dobj);
181
}
182     
183     private static void generateJaxWsImplClass(Project project, FileObject targetFolder, String JavaDoc targetName, URL JavaDoc wsdlURL, final WsdlService service, final WsdlPort port, boolean addService, String JavaDoc serviceID) throws Exception JavaDoc {
184         initProjectInfo(project);
185         
186         // Use Progress API to display generator messages.
187
//ProgressHandle handle = ProgressHandleFactory.createHandle(NbBundle.getMessage(JaxWsUtils.class, "TXT_WebServiceGeneration")); //NOI18N
188
//handle.start(100);
189
JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
190
191         FileObject implClassFo = GenerationUtils.createClass(targetFolder, targetName, null);
192         
193         ClassPath classPath = ClassPath.getClassPath(implClassFo, ClassPath.SOURCE);
194         String JavaDoc serviceImplPath = classPath.getResourceName(implClassFo, '.', false);
195         String JavaDoc portJavaName = port.getJavaName();
196         String JavaDoc artifactsPckg = portJavaName.substring(0, portJavaName.lastIndexOf("."));
197         if (addService) {
198             serviceID = jaxWsSupport.addService(targetName, serviceImplPath, wsdlURL.toString(), service.getName(), port.getName(), artifactsPckg, jsr109Supported && Util.isJavaEE5orHigher(project));
199         }
200         
201         final String JavaDoc wsdlLocation = jaxWsSupport.getWsdlLocation(serviceID);
202         JavaSource targetSource = JavaSource.forFileObject(implClassFo);
203         CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
204
205             public void run(WorkingCopy workingCopy) throws java.io.IOException JavaDoc {
206                 workingCopy.toPhase(Phase.RESOLVED);
207                 GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
208                 if (genUtils!=null) {
209                     TreeMaker make = workingCopy.getTreeMaker();
210                     ClassTree javaClass = genUtils.getClassTree();
211                     
212                     // add implementation clause
213
ClassTree modifiedClass = genUtils.addImplementsClause(javaClass, port.getJavaName());
214                     
215                     //add @WebService annotation
216
TypeElement WSAn = workingCopy.getElements().getTypeElement("javax.jws.WebService"); //NOI18N
217
List JavaDoc<ExpressionTree> attrs = new ArrayList JavaDoc<ExpressionTree>();
218                     attrs.add(
219                         make.Assignment(make.Identifier("serviceName"), make.Literal(service.getName()))); //NOI18N
220
attrs.add(
221                         make.Assignment(make.Identifier("portName"), make.Literal(port.getName()))); //NOI18N
222
attrs.add(
223                         make.Assignment(make.Identifier("endpointInterface"), make.Literal(port.getJavaName()))); //NOI18N
224
attrs.add(
225                         make.Assignment(make.Identifier("targetNamespace"), make.Literal(port.getNamespaceURI()))); //NOI18N
226
attrs.add(
227                         make.Assignment(make.Identifier("wsdlLocation"), make.Literal(wsdlLocation))); //NOI18N
228

229                     AnnotationTree WSAnnotation = make.Annotation(
230                         make.QualIdent(WSAn),
231                         attrs
232                     );
233                     modifiedClass = genUtils.addAnnotation(modifiedClass, WSAnnotation);
234                         
235                     // add @Stateless annotation
236
if (projectType == EJB_PROJECT_TYPE) {//EJB project
237
TypeElement StatelessAn = workingCopy.getElements().getTypeElement("javax.ejb.Stateless"); //NOI18N
238
AnnotationTree StatelessAnnotation = make.Annotation(
239                             make.QualIdent(StatelessAn),
240                             Collections.<ExpressionTree>emptyList()
241                         );
242                         modifiedClass = genUtils.addAnnotation(modifiedClass, StatelessAnnotation);
243                     }
244                     
245                     List JavaDoc<WsdlOperation> operations = port.getOperations();
246                     for(WsdlOperation operation: operations) {
247                         
248                         // return type
249
String JavaDoc returnType = operation.getReturnTypeName();
250                         
251                         // create parameters
252
List JavaDoc<WsdlParameter> parameters = operation.getParameters();
253                         List JavaDoc<VariableTree> params = new ArrayList JavaDoc<VariableTree>();
254                         for (WsdlParameter parameter:parameters) {
255                             // create parameter:
256
// final ObjectOutput arg0
257
params.add(make.Variable(
258                                     make.Modifiers(
259                                         Collections.<Modifier>emptySet(),
260                                         Collections.<AnnotationTree>emptyList()
261                                     ),
262                                     parameter.getName(), // name
263
make.Identifier(parameter.getTypeName()), // parameter type
264
null // initializer - does not make sense in parameters.
265
));
266                         }
267                         
268                         // create exceptions
269
Iterator JavaDoc<String JavaDoc> exceptions = operation.getExceptions();
270                         List JavaDoc<ExpressionTree> exc = new ArrayList JavaDoc<ExpressionTree>();
271                         while (exceptions.hasNext()) {
272                             String JavaDoc exception = exceptions.next();
273                             TypeElement excEl = workingCopy.getElements().getTypeElement(exception);
274                             exc.add(make.QualIdent(excEl));
275                         }
276
277                         // create method
278
ModifiersTree methodModifiers = make.Modifiers(
279                             Collections.<Modifier>singleton(Modifier.PUBLIC),
280                             Collections.<AnnotationTree>emptyList()
281                         );
282                         MethodTree method = make.Method(
283                                 methodModifiers, // public
284
operation.getJavaName(), // operation name
285
make.Identifier(returnType), // return type
286
Collections.<TypeParameterTree>emptyList(), // type parameters - none
287
params,
288                                 exc, // throws
289
"{ //TODO implement this method\nthrow new UnsupportedOperationException(\"Not implemented yet.\") }", // body text
290
null // default value - not applicable here, used by annotations
291
);
292                         
293                         modifiedClass = make.addClassMember(modifiedClass, method);
294                     }
295                     workingCopy.rewrite(javaClass, modifiedClass);
296                 }
297             }
298             
299             public void cancel() {
300             }
301         };
302         targetSource.runModificationTask(task).commit();
303         //open in editor
304
DataObject dobj = DataObject.find(implClassFo);
305         openFileInEditor(dobj);
306         
307 // Retouche
308
// JavaClass javaClass = null;
309
// boolean rollback = true;
310
//
311
// JAXWSSupport jaxWsSupport = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
312
//
313
// JavaModel.getJavaRepository().beginTrans(true);
314
// try {
315
// javaClass = JMIGenerationUtil.createClass(targetFolder, targetName);
316
// JMIUtils.addInterface(javaClass, port.getJavaName());
317
//
318
// if (projectType == EJB_PROJECT_TYPE) {//EJB project
319
// Annotation statelessAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.ejb.Stateless", Collections.EMPTY_LIST); //NOI18N
320
// javaClass.getAnnotations().add(statelessAnnotation);
321
// }
322
//
323
// List operations = port.getOperations();
324
// if (operations != null) {
325
// for (int i = 0; i < operations.size(); i++) {
326
// WsdlOperation operation = (WsdlOperation) operations.get(i);
327
// List parameters = operation.getParameters();
328
//
329
// String returnType = operation.getReturnTypeName();
330
// List exceptions = operation.getExceptions();
331
// Method op = JMIGenerationUtil.createMethod(javaClass, operation.getJavaName(), Modifier.PUBLIC, returnType);
332
// JMIUtils.addExceptions(op, exceptions);
333
// if (parameters != null) {
334
// for (int j = 0; j < parameters.size(); j++) {
335
// WsdlParameter parameter = (WsdlParameter) parameters.get(j);
336
// Parameter param = JMIGenerationUtil.createParameter(javaClass, parameter.getName(), parameter.getTypeName());
337
// op.getParameters().add(param);
338
// }
339
// }
340
//
341
// Type type = JavaModel.getDefaultExtent().getType().resolve(returnType);
342
// op.setBodyText(createBody(type));
343
//
344
// javaClass.getFeatures().add(op);
345
//
346
// }
347
// }
348
//
349
// rollback = false;
350
// } finally {
351
// JavaModel.getJavaRepository().endTrans(rollback);
352
// }
353
//
354
// FileObject fo = javaClass == null ? null : JavaModel.getFileObject(javaClass.getResource());
355
// ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
356
// String serviceImplPath = classPath.getResourceName(fo, '.', false);
357
// String portJavaName = port.getJavaName();
358
// String artifactsPckg = portJavaName.substring(0, portJavaName.lastIndexOf("."));
359
//
360
// if (addService) {
361
// serviceID = jaxWsSupport.addService(targetName, serviceImplPath, wsdlURL.toString(), service.getName(), port.getName(), artifactsPckg, jsr109Supported && Util.isJavaEE5orHigher(project));
362
// }
363
// String wsdlLocation = jaxWsSupport.getWsdlLocation(serviceID);
364
//
365
// //add wsdlLocation attribute
366
// rollback = true;
367
// JavaModel.getJavaRepository().beginTrans(true);
368
// try {
369
// AttributeValue serviceNameAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "serviceName", service.getName()); //NOI18N
370
// AttributeValue portNameAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "portName", port.getName()); //NOI18N
371
// AttributeValue endPointInterfaceAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "endpointInterface", port.getJavaName()); //NOI18N
372
// AttributeValue targetNamespaceAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "targetNamespace", port.getNamespaceURI()); //NOI18N
373
// AttributeValue wsdlLocationAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "wsdlLocation", wsdlLocation); //NOI18N
374
//
375
// List attributes = new LinkedList();
376
// attributes.add(serviceNameAttibuteValue);
377
// attributes.add(portNameAttibuteValue);
378
// attributes.add(endPointInterfaceAttibuteValue);
379
// attributes.add(targetNamespaceAttibuteValue);
380
// attributes.add(wsdlLocationAttibuteValue);
381
// Annotation wsAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.jws.WebService", attributes); //NOI18N
382
// javaClass.getAnnotations().add(wsAnnotation);
383
//
384
// // add @javax.xml.ws.BindingType annotation for SOAP12 binding
385
// if (port.getSOAPVersion().equals(WsdlPort.SOAP_VERSION_12)) {
386
// AttributeValue bindingAttibuteValue = JMIGenerationUtil.createAttributeValue(javaClass, "value", WsdlPort.SOAP_VERSION_12); //NOI18N
387
// attributes.clear();
388
// attributes.add(bindingAttibuteValue);
389
// Annotation bindingAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.xml.ws.BindingType", attributes); //NOI18N
390
// javaClass.getAnnotations().add(bindingAnnotation);
391
// }
392
//
393
// rollback = false;
394
// } finally {
395
// JavaModel.getJavaRepository().endTrans(rollback);
396
// }
397
//
398
// //open in the editor
399
// DataObject dobj = DataObject.find(fo);
400
// openFileInEditor(dobj);
401
//
402
// //handle.finish();
403
}
404     
405     private static void openFileInEditor(DataObject dobj){
406         final EditorCookie ec = (EditorCookie)dobj.getCookie(EditorCookie.class);
407         RequestProcessor.getDefault().post(new Runnable JavaDoc(){
408             public void run(){
409                 ec.open();
410             }
411         }, 1000);
412     }
413
414 // Retouche
415
// private static String createBody(Type type) {
416
// String initVal;
417
//
418
// if (type instanceof PrimitiveType) {
419
// PrimitiveTypeKind primitiveType = ((PrimitiveType) type).getKind();
420
// if (PrimitiveTypeKindEnum.BOOLEAN.equals(primitiveType)) {
421
// initVal = "false"; // NOI18N
422
// } else if (PrimitiveTypeKindEnum.CHAR.equals(primitiveType)) {
423
// initVal = "'\\0'"; // NOI18N
424
// } else if (PrimitiveTypeKindEnum.VOID.equals(primitiveType)) {
425
// return "throw new UnsupportedOperationException(\"Not yet implemented\");"; // NOI18N
426
// } else {
427
// initVal = "0"; // NOI18N
428
// }
429
// } else if (type instanceof ClassDefinition) {
430
// initVal = "null"; // NOI18N
431
// } else {
432
// throw new IllegalArgumentException("Type "+type.getClass()); // NOI18N
433
// }
434
// return "return ".concat(initVal).concat(";"); // NOI18N
435
// }
436

437     private static void initProjectInfo(Project project) {
438         JAXWSSupport wss = JAXWSSupport.getJAXWSSupport(project.getProjectDirectory());
439         if (wss != null) {
440             Map JavaDoc properties = wss.getAntProjectHelper().getStandardPropertyEvaluator().getProperties();
441             String JavaDoc serverInstance = (String JavaDoc)properties.get("j2ee.server.instance"); //NOI18N
442
if (serverInstance != null) {
443                 J2eePlatform j2eePlatform = Deployment.getDefault().getJ2eePlatform(serverInstance);
444                 if (j2eePlatform != null) {
445                     jwsdpSupported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_JWSDP); //NOI18N
446
jsr109Supported = j2eePlatform.isToolSupported(J2eePlatform.TOOL_JSR109);
447                 }
448             }
449         }
450         
451         WebModule wm = WebModule.getWebModule(project.getProjectDirectory());
452         EjbJar em = EjbJar.getEjbJar(project.getProjectDirectory());
453         if (em != null)
454             projectType = EJB_PROJECT_TYPE;
455         else if (wm != null)
456             projectType = WEB_PROJECT_TYPE;
457         else
458             projectType = JSE_PROJECT_TYPE;
459     }
460     
461     public static boolean isProjectReferenceable(Project clientProject, Project targetProject) {
462         if (clientProject==targetProject) {
463             return true;
464         } else {
465             ProjectClassPathExtender pce = (ProjectClassPathExtender)targetProject.getLookup().lookup(ProjectClassPathExtender.class);
466             AntArtifactProvider antArtifactProvider = (AntArtifactProvider)clientProject.getLookup().lookup(AntArtifactProvider.class);
467             if (antArtifactProvider!=null) {
468                 AntArtifact jarArtifact = getJarArtifact(antArtifactProvider);
469                 if (jarArtifact!=null) return true;
470             }
471             return false;
472         }
473     }
474     
475     public static boolean addProjectReference(Project clientProject, Project targetProject) {
476         try {
477             assert clientProject!=null && targetProject!=null;
478             if (clientProject!=targetProject) {
479                 ProjectClassPathExtender pce = (ProjectClassPathExtender)targetProject.getLookup().lookup(ProjectClassPathExtender.class);
480                 AntArtifactProvider antArtifactProvider = (AntArtifactProvider)clientProject.getLookup().lookup(AntArtifactProvider.class);
481                 if (antArtifactProvider!=null) {
482                     AntArtifact jarArtifact = getJarArtifact(antArtifactProvider);
483                     if (jarArtifact!=null) {
484                         URI JavaDoc[] artifactsUri = jarArtifact.getArtifactLocations();
485                         for (int i=0;i<artifactsUri.length;i++) {
486                             pce.addAntArtifact(jarArtifact,artifactsUri[i]);
487                         }
488                         return true;
489                     }
490                 }
491             } else {
492                 return true;
493             }
494         } catch (IOException JavaDoc ex) {
495             ErrorManager.getDefault().log(ex.getLocalizedMessage());
496         }
497         return false;
498     }
499     
500     private static AntArtifact getJarArtifact(AntArtifactProvider antArtifactProvider) {
501         AntArtifact[] artifacts = antArtifactProvider.getBuildArtifacts();
502         for (int i=0;i<artifacts.length;i++) {
503             if (JavaProjectConstants.ARTIFACT_TYPE_JAR.equals(artifacts[i].getType())) return artifacts[i];
504         }
505         return null;
506     }
507     
508     public static class WsImportServiceFailedMessage extends NotifyDescriptor.Message {
509         public WsImportServiceFailedMessage(Throwable JavaDoc ex) {
510             super(NbBundle.getMessage(JaxWsUtils.class,"TXT_CannotGenerateService",ex.getLocalizedMessage()),
511                     NotifyDescriptor.ERROR_MESSAGE);
512         }
513     }
514     
515     public static class WsImportClientFailedMessage extends NotifyDescriptor.Message {
516         public WsImportClientFailedMessage(Throwable JavaDoc ex) {
517             super(NbBundle.getMessage(JaxWsUtils.class,"TXT_CannotGenerateClient",ex.getLocalizedMessage()),
518                     NotifyDescriptor.ERROR_MESSAGE);
519         }
520     }
521     
522     /**
523      * Utility for changing the wsdlLocation attribute in external JAXWS external files
524      * @param bindingFile FileObject of the external binding file
525      * @param relativePath String representing the relative path to the wsdl
526      * @return true if modification succeeded, false otherwise.
527      */

528     public static boolean addRelativeWsdlLocation(FileObject bindingFile, String JavaDoc relativePath) {
529         GlobalBindings gb = null;
530         
531             ModelSource ms = org.netbeans.modules.xml.retriever.catalog.Utilities.getModelSource(bindingFile, true);
532             if(ms != null){
533                 BindingsModel bindingsModel = BindingsModelFactory.getDefault().getModel(ms);
534                 if(bindingsModel != null){
535                     gb = bindingsModel.getGlobalBindings();
536                     if(gb != null){
537                         bindingsModel.startTransaction();
538                         gb.setWsdlLocation(relativePath);
539                         bindingsModel.endTransaction();
540                         return true;
541                     }
542                 }
543             }
544         return false;
545     }
546     /** Package name validation
547      */

548     public static boolean isJavaPackage(String JavaDoc pkg) {
549         boolean result = false;
550         
551         if(pkg != null && pkg.length() > 0) {
552             int state = 0;
553             for(int i = 0, pkglength = pkg.length(); i < pkglength && state < 2; i++) {
554                 switch(state) {
555                     case 0:
556                         if(Character.isJavaIdentifierStart(pkg.charAt(i))) {
557                             state = 1;
558                         } else {
559                             state = 2;
560                         }
561                         break;
562                     case 1:
563                         if(pkg.charAt(i) == '.') {
564                             state = 0;
565                         } else if(!Character.isJavaIdentifierPart(pkg.charAt(i))) {
566                             state = 2;
567                         }
568                         break;
569                 }
570             }
571             
572             if(state == 1) {
573                 result = true;
574             }
575         }
576         
577         return result;
578     }
579     
580     /** Class/Identifier validation
581      */

582     public static boolean isJavaIdentifier(String JavaDoc id) {
583         boolean result = true;
584         
585         if(id == null || id.length() == 0 || !Character.isJavaIdentifierStart(id.charAt(0))) {
586             result = false;
587         } else {
588             for(int i = 1, idlength = id.length(); i < idlength; i++) {
589                 if(!Character.isJavaIdentifierPart(id.charAt(i))) {
590                     result = false;
591                     break;
592                 }
593             }
594         }
595         
596         return result;
597     }
598     
599     /** This method ensures the list of steps displayed in the left hand panel
600      * of the wizard is correct for any given displayed panel.
601      *
602      * Taken from web/core
603      */

604     public static String JavaDoc[] createSteps(String JavaDoc[] before, WizardDescriptor.Panel[] panels) {
605         //assert panels != null;
606
// hack to use the steps set before this panel processed
607
int diff = 0;
608         if (before == null) {
609             before = new String JavaDoc[0];
610         } else if (before.length > 0) {
611             diff = ("...".equals(before[before.length - 1])) ? 1 : 0; // NOI18N
612
}
613         String JavaDoc[] res = new String JavaDoc[ (before.length - diff) + panels.length];
614         for (int i = 0; i < res.length; i++) {
615             if (i < (before.length - diff)) {
616                 res[i] = before[i];
617             } else {
618                 res[i] = panels[i - before.length + diff].getComponent().getName();
619             }
620         }
621         return res;
622     }
623 }
624
Popular Tags