Version 3.1 by Pascal Robert on 2007/09/03 19:49

Hide last authors
smmccraw 1.1 1 WebObjects supports Web Services both as a producer and a consumer, and it actually works quite well once you figure out how to get things properly configured. Hopefully this walkthrough can jumpstart that process for you.
2
Pascal Robert 3.1 3 = Setting up a WO Web Services Project =
smmccraw 1.1 4
5 Here are the basic steps for setting up a Web Services producer with WebObjects and Eclipse/WOLips:
6
7 1. Create a new WOApplication project
8 1. Edit the project's Build Path, and go to the Libraries tab
9 11. Add the following external jars from /Library/WebObjects/Extensions.
10 11*. axis.jar
11 11*. commons-logging.jar
12 11*. commons-discovery.jar
13 11*. wsdl4j.jar
14 11*. saaj.jar
15 11*. jaxrpc.jar
16 11. Edit the WO Frameworks collection and add the JavaWebServicesSupport framework from the System frameworks
17 1. Create a class to hold your web service methods. The methods do not need to be static and can both take complex types as parameters and return complex types as return values. For now, just return primitive types and/or String.
18 1. Edit your Application class and add WOWebServiceRegistrar.registerWebService("PublishedNameOfYourWebService", NameOfTheClassYouJustMade.class, true);
19
Pascal Robert 3.1 20 That's it. Now when you start your app, you can request [[http://yourserver.com/cgi-bin/WebObjects/YourApp.woa/ws/PublishedNameOfYourWebService?wsdl]] and it will return the autogenerated WSDL document that you can use with any number of web service clients to interact with your server.
smmccraw 1.1 21
Pascal Robert 3.1 22 = Complex Types with WO Web Services =
smmccraw 1.1 23
Pascal Robert 3.1 24 So now the issue of complex types. Returning complex types is fine, but you have to register the serializer and deserializer classes for each complex type you reference. If you do not, the server will attempt to serialize your object using the ArraySerializer (you'll see this exception on the server), and the client will complain about a nonsensical error with SYSTEMID (gotta love terrible error handling). The fix for this is for each of your complex types, call the following method in your Application constructor:
smmccraw 1.1 25
26 {{panel}}
27
Pascal Robert 3.1 28 WOWebServiceRegistrar.registerFactoriesForClassWithQName(new BeanSerializerFactory(_class, \_qName), new BeanDeserializerFactory(_class, \_qName), \_class, \_qName);
smmccraw 1.1 29
30 {{/panel}}
31
Pascal Robert 3.1 32 where class is the Class object that represents your complex type, and qName is the QName (fully qualified name) of the class as it appears in your WSDL document. For instance, if you created a complex return type named Person and it is in the com.yourserver.service package, class would be com.yourserver.service.Person.class and qName would be new QName("http:~/~/service.yourserver.com", "Person"). Notice that the namespace is the inverse of your package name. You will need to call this method for each of the parameters and return types your reference.
smmccraw 1.1 33
Pascal Robert 3.1 34 For the record, I have no idea why you have to do this step manually - The WSDL was autogenerated, and thus it KNOWS the classes and their QName WSDL mappings, but I was not able to get things to work properly without this step. If anyone knows why this is, or a way around it, please update this article.
smmccraw 1.1 35
36 With these registrations, you should now be able to communicate with WO using any standard Web Service client (Axis, .NET, etc).
37
Pascal Robert 3.1 38 = Sessions and WO Web Services =
smmccraw 1.1 39
40 You may have noticed in your Web Service methods that you have no WOContext, WORequest, WOSession, and friends passed in. Do not fret. The WebServiceRequestHandler takes care to hook you up in this department using Axis's MessageContext class. You can use the following code to get to your WOSession:
41
42 {{panel}}
43
Pascal Robert 3.1 44 WOContext context = (WOContext)MessageContext.getCurrentContext().getProperty("com.webobjects.appserver.WOContext");
45 WOSession session = context.session();
smmccraw 1.1 46
47 {{/panel}}
48
49 or the shortcut
50
51 {{panel}}
52
Pascal Robert 3.1 53 WOSession session = WOWebServiceUtilities.currentWOContext().session();
smmccraw 1.1 54
55 {{/panel}}
56
57 The following additional keys are accessible through the MessageContext:
58
59 * "com.webobjects.appserver.WOContext" = the WOContext for this request
60 * "transport.url" = I /believe/ this contains the full request URL up to the query string
61 * org.apache.axis.transport.http.HTTPConstants.MC//HTTP//SERVLETPATHINFO = contains the request's request handler path
62 * "Authorization" = contains the Authorization header, in the event that you need to process things like Kerberos/SPNEGO, etc.
63 * "remoteaddr" = contains the request's remote address
64
Pascal Robert 3.1 65 = Consuming with Axis in Java =
smmccraw 1.1 66
Pascal Robert 3.1 67 If you are using Axis to consume a WO Web Service, be advised that there is an outstanding bug (open since circa 2003, no less) that axis by default does not support passing more than one cookie to the server. WO sends both woinst AND wosid, so you lose your session ID from the client on the return trip to the server. This can be fixed by applying the patch from [[http://issues.apache.org/jira/browse/AXIS-1059]] to your client's axis.jar. Axis 1.1 has been archived at Apache, but you can download the source from [[http://archive.apache.org/dist/ws/axis/1_1/]] . The patch does not perfectly apply. There are two rejected hunks, but it should be very obvious how to fix the rejects (the patch has two System.out.printlns that it claims were in the original source that were not). After fixing that, you can setStoreSessionIdInCookies(true) on your server's WOSession and setMaintainSessions(true) on your client's ServiceLocator and you'll be good to go.
smmccraw 1.1 68
69 This Axis bug appears to be fixed in recent versions of Axis, including version 1.4. Trying to upgrade the version of Axis in your WO Web Services server is not likely to be a happy experience (and likely neither will be upgrading Axis in a Direct To Web Services client - though I haven't tried this). However, it does seem to be possible to use a later version of the Axis jars on the classpath of a WebObjects application that intends to use classes generated by WSDL2Java to connect to a remote Web Services server - assuming that there are no WebObjects classes included in the WSDL. It is important in this case that you use matching version of WSDL2Java.
70
Pascal Robert 3.1 71 = Consuming with WebServicesCore.framework =
smmccraw 1.1 72
73 There are several complications when it comes to using WebServicesCore with WebObjects, all of which stem from the WSMakeStubs generated code. Upon using the code generated by WSMakeStubs, you will run into the following issues that need to be fixed in its code:
74
Pascal Robert 3.1 75 = WSMakeStubs =
smmccraw 1.1 76
77 Apple provides a program called WSMakeStubs that is similar to WSDL2Java in Axis, except that it sucks. It will, however, at least give you a starting point for building your web service client code, and with the changes outlined below, you can end up with decent client APIs.
78
79 Running WSMakeStubs is very simple:
80
Pascal Robert 3.1 81 /Developer/Tools/WSMakeStubs x ObjC name NameOfServiceClass url [[http://yourserver.com/cgi-bin/WebObjects/YourWOA.woa/ws/YourService?wsdl]]
smmccraw 1.1 82
Pascal Robert 3.1 83 This will produce Objective-C code that you can use to call your web service. As opposed to Axis, WSMakeStubs produces stateless code for your service (i.e. no session tracking or cookie support - only static methods for each method of your web service). All of the methods appear at the end of NameOfServiceClass.m that you will need to call. WSMakeStubs also produces WSGeneratedObj.m, which contains the lower level web service core calls.
smmccraw 1.1 84
Pascal Robert 3.1 85 = Service Methods Without Return Values =
smmccraw 1.1 86
Pascal Robert 3.1 87 Another bug in WSMakeStubs is related to methods that don't have return values. For void methods, the methods are never actually CALLED by WSMakeStubs. If you look at the code for the returnValue method, you will see that it never calls [[WO:super getResultDictionary]]. The problem with this is that [[WO:super getResultDictionary]] is the code that actually executes the web service method. Simply change the definition for your void method to be:
smmccraw 1.1 88
Pascal Robert 3.1 89 {{code}}
smmccraw 1.1 90
Pascal Robert 3.1 91 - (id) resultValue {
92 return [self getResultDictionary];
93 }
smmccraw 1.1 94
95
Pascal Robert 3.1 96 {{/code}}
97
smmccraw 1.1 98 And everything will work as planned.
99
Pascal Robert 3.1 100 = Bugs and Changes to WSGeneratedObj =
smmccraw 1.1 101
102 WSGeneratedObj is MOSTLY bug free. However, there there are a couple changes required to fix a memory leak it generates (from cocoadev.com):
103
104 At the end of getResultDictionary, add:
105
Pascal Robert 3.1 106 {{code}}
smmccraw 1.1 107
Pascal Robert 3.1 108 if (fRef) { // new code
109 WSMethodInvocationSetCallBack(fRef, NULL, NULL); // new code
110 } // new code
111 return fResult; // original code
smmccraw 1.1 112
Pascal Robert 3.1 113 {{/code}}
smmccraw 1.1 114
115 which now reveals that the NSURL that is used is double-freed, fixable by removing one line from createInvocationRef:
116
Pascal Robert 3.1 117 {{code}}
smmccraw 1.1 118
Pascal Robert 3.1 119 NSURL* url = [NSURL URLWithString: endpoint];
120 if (url == NULL) {
121 [self handleError: @"NSURL URLWithString failed in createInvocationRef" errorString:NULL errorDomain:kCFStreamErrorDomainMacOSStatus errorNumber:paramErr];
122 } else {
123 ref = WSMethodInvocationCreate((CFURLRef) url, (CFStringRef)methodName, (CFStringRef) protocol);
124 // [url release]; remove this line
125 ....
smmccraw 1.1 126
Pascal Robert 3.1 127 {{/code}}
smmccraw 1.1 128
129 Another change I like to make in the generated is to remove the hard-coded service URLs and pass them in from the code that calls the service (much like Axis does). This should be a fairly straightforward change, but I wanted to make a note about doing it. It will be fairly common that you want to talk to a development server and a production server using the same code, and as a result, you will want that variable to be parameterized.
130
Pascal Robert 3.1 131 = Passing a Complex Type to WO =
smmccraw 1.1 132
Pascal Robert 3.1 133 WSMakeStubs provides no direct support for passing complex types around - All you get is an NSDictionary, and all you can send back is an NSDictionary, with no instructions as to what exactly is IN these dictionaries.
smmccraw 1.1 134
135 To send a complex type back to WO, you have to set the following keys in your dictionary:
136
Pascal Robert 3.1 137 {{code}}
smmccraw 1.1 138
Pascal Robert 3.1 139 [dictionary setObject:@"http://extranet.mdtask.mdimension.com" forKey:(NSString *)kWSRecordNamespaceURI];
140 [dictionary setObject:@"WSCompany" forKey:(NSString *)kWSRecordType];
smmccraw 1.1 141
Pascal Robert 3.1 142 {{/code}}
smmccraw 1.1 143
144 Where kWSRecordNamespaceURI's value is the XML namespace of the type of the complex object you are passing, and kWSRecordType's value is the name of the type. On the WO side, the namespace will be the reverse of the type's class name, and the record type will be the name of the class. For instance, in the example above, the actual class on the server was named com.mdimension.mdtask.extranet.WSCompany .
145
146 The rest of the dictionary contains attribute=>value mappings. For instance, WSCompany in the example above has a "name" attribute, so the dictionary would also contains a "name" key that maps to the corresponding value.
147
Pascal Robert 3.1 148 When sending NSDictionary instances from Cocoa, the WO will fire the WOGlobalIDDeserializer and it will not properly parse the nsdictionary or nsarray, it appears that there is no default deserializer on the WO side for those classes.
smmccraw 1.1 149
150 One solution is to add
151
Pascal Robert 3.1 152 {{code}}
smmccraw 1.1 153
Pascal Robert 3.1 154 @implementation NSObject (NSObject_WOXML)
smmccraw 1.1 155
Pascal Robert 3.1 156 - (NSString*)xmlPlist {
157 NSString* error;
158 NSData* data = [NSPropertyListSerialization dataFromPropertyList:self
159 format:NSPropertyListXMLFormat_v1_0
160 errorDescription:&error];
161 return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
162 }
smmccraw 1.1 163
Pascal Robert 3.1 164 @end
smmccraw 1.1 165
Pascal Robert 3.1 166 {{/code}}
smmccraw 1.1 167
Pascal Robert 3.1 168 on the cocoa side, than call it when compiling the arguments for the WSMethodInvocationRef
169 Than on the WO side use NSPropertyListSerialization.propertyListFromString(xmlPlist) to recreate the object.
smmccraw 1.1 170
Pascal Robert 3.1 171 = Return Values from WO =
smmccraw 1.1 172
Pascal Robert 3.1 173 One of the other problems WSMakeStubs has is that it doesn't produce a valid identifier for retrieving a WO web service return value. In the generated code, you will see something like
smmccraw 1.1 174
Pascal Robert 3.1 175 {{code}}
smmccraw 1.1 176
Pascal Robert 3.1 177 - (id) resultValue {
178 return [[super getResultDictionary] objectForKey: @"getBillableCompaniesReturn"];
179 }
smmccraw 1.1 180
181
Pascal Robert 3.1 182 {{/code}}
smmccraw 1.1 183
Pascal Robert 3.1 184 however, the actual return value name requires its namspace to be included. The fixed version of the routine looks like:
smmccraw 1.1 185
Pascal Robert 3.1 186 {{code}}
smmccraw 1.1 187
Pascal Robert 3.1 188 - (id) resultValue {
189 return [[super getResultDictionary] objectForKey: @"ns1:getBillableCompaniesReturn"];
190 }
smmccraw 1.1 191
Pascal Robert 3.1 192 {{/code}}
smmccraw 1.1 193
Pascal Robert 3.1 194 Notice the key starts with "ns1:". This value should match the value that appears in your WSDL.
smmccraw 1.1 195
Pascal Robert 3.1 196 = Example Type Wrappers =
smmccraw 1.1 197
Pascal Robert 3.1 198 Here's an example type wrapper I use based on the WSCompany example above. In the static methods that WSMakeStubs creates that wrap my web service methods, I simply initWithDictionary this type with the result dictionary from the web service and return an instance of WSCompany rather than the dictionary. When I send one of these objects back, I simply send [[WO:wsCompany dictionary]] in the wrapper method.
smmccraw 1.1 199
Pascal Robert 3.1 200 {{code}}
smmccraw 1.1 201
Pascal Robert 3.1 202 @interface WSCompany : NSObject {
203 NSMutableDictionary *myDictionary;
204 }
smmccraw 1.1 205
Pascal Robert 3.1 206 -(id)initWithDictionary:(NSDictionary *)_dictionary;
207 -(NSDictionary *)dictionary;
208 -(NSString *)name;
209 -(NSString *)companyID;
210 @end
smmccraw 1.1 211
Pascal Robert 3.1 212 {{/code}}
smmccraw 1.1 213
Pascal Robert 3.1 214 {{code}}
smmccraw 1.1 215
Pascal Robert 3.1 216 @implementation WSCompany
smmccraw 1.1 217
Pascal Robert 3.1 218 -(id)initWithDictionary:(NSDictionary *)_dictionary {
219 self = [super init];
220 myDictionary = [[_dictionary mutableCopy] retain];
221 [myDictionary setObject:@"http://extranet.mdtask.mdimension.com" forKey:(NSString *)kWSRecordNamespaceURI];
222 [myDictionary setObject:@"WSCompany" forKey:(NSString *)kWSRecordType];
223 return self;
224 }
smmccraw 1.1 225
Pascal Robert 3.1 226 -(void)dealloc {
227 [myDictionary release];
228 [super dealloc];
229 }
smmccraw 1.1 230
Pascal Robert 3.1 231 -(NSDictionary *)dictionary {
232 return myDictionary;
233 }
smmccraw 1.1 234
Pascal Robert 3.1 235 -(NSString *)name {
236 return [myDictionary objectForKey:@"name"];
237 }
smmccraw 1.1 238
Pascal Robert 3.1 239 -(NSString *)companyID {
240 return [myDictionary objectForKey:@"companyID"];
241 }
242 @end
smmccraw 1.1 243
Pascal Robert 3.1 244 {{/code}}
smmccraw 1.1 245
Pascal Robert 3.1 246 = Fault Handling =
smmccraw 1.1 247
Pascal Robert 3.1 248 WSMakeStubs doesn't handle the fault properly but it's in the dictionary. In resultForInvocation: I added a few lines to check for and return the fault
smmccraw 1.1 249
Pascal Robert 3.1 250 {{code}}
smmccraw 1.1 251
Pascal Robert 3.1 252 + (id) resultForInvocation:(WSGeneratedObj*)invocation; {
253 result = [[invocation resultValue] retain];
254 // Added check if a fault occured and return the fault string if so
255 if([invocation isComplete]) {
256 if([invocation isFault]) {
257 result = [[invocation getResultDictionary] valueForKey:@"/FaultString"];
258 }
259 }
260 //
261 [invocation release];
262 return result;
263 }
smmccraw 1.1 264
265
Pascal Robert 3.1 266 {{/code}}
smmccraw 1.1 267
Pascal Robert 3.1 268 = Stateful Services =
smmccraw 1.1 269
270 Below is the necessary code to enable cookie support and stateful session with the files generated by WSMakeStubs. This code also includes changes so the base web services URL is supplied in the init method and allows specifying a timeout value (which I defaulted to 30 seconds). To WSGeneratedObj.h, add three new member variables:
271
Pascal Robert 3.1 272 {{code}}
smmccraw 1.1 273
Pascal Robert 3.1 274 @interface WSGeneratedObj : NSObject {
275 WSMethodInvocationRef fRef;
276 NSDictionary* fResult;
277 NSDictionary* fCookies;
278 NSString fURLString;
279 int fTimeout;
smmccraw 1.1 280
Pascal Robert 3.1 281 id fAsyncTarget;
282 SEL fAsyncSelector;
283 };
smmccraw 1.1 284
Pascal Robert 3.1 285 {{/code}}
286
smmccraw 1.1 287 Here are the new methods to add to WSGeneratedObject.m:
288
Pascal Robert 3.1 289 {{code}}
smmccraw 1.1 290
Pascal Robert 3.1 291 -- (id) initWithWebServicesURLString:(NSString*)urlString
292 {
293 if (self = [super init]) {
294 fURLString = [urlString copy];
295 }
296 return self;
297 }
smmccraw 1.1 298
Pascal Robert 3.1 299 - (NSString*) getWebServicesURLString { return fURLString; }
smmccraw 1.1 300
Pascal Robert 3.1 301 - (NSURL*) getWebServicesURL { return [NSURL URLWithString: [self getWebServicesURLString]]; }
smmccraw 1.1 302
Pascal Robert 3.1 303 - (NSArray*) getReturnedCookies
304 {
305 NSDictionary *results = [self getResultDictionary];
306 if (nil == results)
307 return nil;
308 CFHTTPMessageRef msgRef = (CFHTTPMessageRef)[results objectForKey: (id)kWSHTTPResponseMessage];
309 NSDictionary *headers = (NSDictionary*)CFHTTPMessageCopyAllHeaderFields(msgRef);
310 [headers autorelease];
311 //parse the cookies
312 NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL: [self getWebServicesURL]];
313 return cookies;
314 }
smmccraw 1.1 315
Pascal Robert 3.1 316 - (void) setCookies:(NSArray*)cookies
317 {
318 [fCookies release];
319 fCookies = [[NSHTTPCookie requestHeaderFieldsWithCookies: cookies] retain];
320 WSMethodInvocationSetProperty([self getRef], kWSHTTPExtraHeaders, fCookies);
321 }
smmccraw 1.1 322
Pascal Robert 3.1 323 {{/code}}
smmccraw 1.1 324
Pascal Robert 3.1 325 {{code}}
smmccraw 1.1 326
Pascal Robert 3.1 327  - (int)timeoutValue { return fTimeout; }
328 - (void)setTimeout:(int)t
329 {
330 if (t >= 0 && t < 600)
331 fTimeout = 30;
332 }
smmccraw 1.1 333
334
Pascal Robert 3.1 335 {{/code}}
smmccraw 1.1 336
Pascal Robert 3.1 337 You will need to modify dealloc to release fCookies and fURLString. Below is my modified version getCreateInvocationRef. It is modified to get the URL using the new accessor methods above, to get the method name from the class name (which makes a lot more sense than hard-coding it to the class name in every subclass), and to set the timeout. After that is a generic resultValues method so that your generated subclasses can have their resultValues and getCreateInvocationRef methods removed~-~--the only methods they require are for setting parameters. There is also a commented out line that you can uncomment to have debug information included in the results dictionary. This is very helpful when trying to debug the transfer of complex objects.
338
339 {{code}}
340
341 - (WSMethodInvocationRef) genCreateInvocationRef
342 {
343 WSMethodInvocationRef invRef = [self createInvocationRef
344 /*endpoint*/: [self getWebServicesURLString]
345 methodName: NSStringFromClass([self class])
346 protocol: (NSString*) kWSSOAP2001Protocol
347 style: (NSString*) kWSSOAPStyleRPC
348 soapAction: @""
349 methodNamespace: @"http://DefaultNamespace"];
350 //set a time-out value
351 if (fTimeout > 0) {
352 WSMethodInvocationSetProperty(invRef, kWSMethodInvocationTimeoutValue, (CFTypeRef)[NSNumber numberWithInt: fTimeout]);
353 // WSMethodInvocationSetProperty(invRef, kWSDebugIncomingBody, (CFTypeRef)kCFBooleanTrue);
354 }
355 return invRef;
356 }
357
358 - (id) resultValue
359 {
360 NSString *key = [NSString stringWithFormat: @"ns1:%@Return", NSStringFromClass([self class])];
361 return [[self getResultDictionary] objectForKey: key];
362 }
363
364
365 {{/code}}
366
smmccraw 1.1 367 To use stateful services, call getReturnedCookies after the first request and store the cookie dictionary. Then call setCookies: with that dictionary on all of your subsequent web services calls. Depending on the cookies you use, you might want to save a new copy of the cookies dictionary after each request.