summaryrefslogtreecommitdiff
path: root/java/management/client/src/main/java/org/apache/qpid/management/wsdm/capabilities/WsdlBuilder.java
blob: 6bfccda1ce0cd59625ac66c5da3201b73e45aacf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.management.wsdm.capabilities;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ObjectName;
import javax.xml.transform.TransformerException;

import org.apache.muse.core.Environment;
import org.apache.muse.core.serializer.SerializerRegistry;
import org.apache.muse.util.ReflectUtils;
import org.apache.muse.util.xml.XmlUtils;
import org.apache.muse.ws.wsdl.WsdlUtils;
import org.apache.qpid.management.Messages;
import org.apache.qpid.management.Names;
import org.apache.qpid.management.wsdm.muse.engine.WSDMAdapterEnvironment;
import org.apache.qpid.management.wsdm.muse.serializer.ObjectSerializer;
import org.apache.qpid.qman.debug.WsdlDebugger;
import org.apache.qpid.transport.util.Logger;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
 * TO BE IMPROVED USING JAXB!!
 * 
 * @author Andrea Gazzarini
 */
class WsdlBuilder implements IArtifactBuilder,Constants {

	private final static Logger LOGGER = Logger.get(WsdlBuilder.class);
	
	private WSDMAdapterEnvironment _environment;
	private Document _document;
	private Element schema;
	private Element _wsrpProperties;
	private ObjectSerializer _serializer;
	private ObjectName _objectName;
	private Map<String, String> arrayTypesAlreadyDeclared = new HashMap<String, String>();
	
	private Element _arrayComplexType;
	private Element _nestedArrayType;
	
	/**
	 * For each attibute the corresponding xml type definition must be inserted on the QMan
	 * schema related section.
	 * After that, a reference to that definition must be declared on the wsrp element .
	 * 
	 * @param attributeMetadata the attribute metadata.
	 * @throws BuilderException only if this builder wasn't able to get a reference (via XPath) 
	 * 				to QMan schema section.
	 */
	public void onAttribute(MBeanAttributeInfo attributeMetadata) throws BuilderException  
	{
		try 
		{
			String attributeName = attributeMetadata.getName();
			schema.appendChild(defineSchemaFor(attributeMetadata.getType(), attributeName));				

			Element propertyRef= XmlUtils.createElement(_document, XSD_ELEMENT_QNAME);
			propertyRef.setAttribute(MIN_OCCURS, "0");		
			propertyRef.setAttribute(
					REF_ATTRIBUTE, 
					Names.PREFIX+":"+attributeName);

			_wsrpProperties.appendChild(propertyRef);
		} catch(Exception exception)
		{
			throw new BuilderException(exception);
		}
	}
	
	@SuppressWarnings("unchecked")
	private Element defineSchemaFor(String type, String attributeName) throws Exception
	{
		Element propertyDeclaration = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME);
		String xmlType = null;
		if (type.equals(Map.class.getName())) 
		{
			xmlType="qman:map";
		} else if (UUID.class.getName().equals(type)) 
		{			
			xmlType = "qman:uuid";
		} else if (type.startsWith("["))
		{
			Class arrayClass =  Class.forName(type);
			Class clazz = ReflectUtils.getClassFromArrayClass(arrayClass);
			String arrayType = arrayClass.getSimpleName().replace("[]", "").trim();
			arrayType = Character.toUpperCase(arrayType.charAt(0))+arrayType.substring(1);
			if (!arrayTypesAlreadyDeclared.containsKey(type))
			{
				_arrayComplexType.setAttribute(NAME_ATTRIBUTE, "arrayOf"+arrayType);
				_nestedArrayType.setAttribute(TYPE_ATTRIBUTE, _serializer.getXmlType(clazz));
				schema.appendChild(_arrayComplexType);
				arrayTypesAlreadyDeclared.put(type, arrayType);
			}
			xmlType = "qman:arrayOf"+arrayTypesAlreadyDeclared.get(type);
		}
		else 
		{			
			xmlType = _serializer.getXmlType(Class.forName(type));
		}			
		propertyDeclaration.setAttribute(NAME_ATTRIBUTE,attributeName);
		propertyDeclaration.setAttribute(TYPE_ATTRIBUTE, xmlType);
		return propertyDeclaration;
	}

	/**
	 * Initializes this builder.
	 * 
	 * @param objectName the name of the current JMX entity.
	 * @throws BuilderException when it's not possible to proceed with the initialization.
	 */
	public void begin(ObjectName objectName) throws BuilderException
	{
		this._objectName = objectName;
		this._serializer = (ObjectSerializer) SerializerRegistry.getInstance().getSerializer(Object.class);
		
		createWsrpPropertiesElement();
		
		createReusableArrayComplextType();
		
		replaceDummyServiceLocationOnWsdl();
		
		createSchemaElement();
	}
	
	public void onOperation(MBeanOperationInfo operationMetadata) throws BuilderException
	{
		// SCHEMA SECTION
		/*
			<xs:element name='purgeRequest' type='qman:purgeRequest' />
			
			<xs:element name='purgeResponse' type='qman:purgeResponse' />
			
			<xs:complexType name='purgeRequest'>
				<xs:sequence>
					<xs:element name='arg0' type='xs:int' />
					<xs:element minOccurs='0' name='arg1' type='qman:hashMap' />
				</xs:sequence>
			</xs:complexType>
			
			<xs:element name='hashMap'>
	        	<xs:complexType>
	         		<xs:sequence>
	          			<xs:element maxOccurs='unbounded' minOccurs='0' name='entry'>
	           				<xs:complexType>
	            				<xs:sequence>
	             					<xs:element minOccurs='0' name='key' type='xs:string'/>
	             					<xs:element minOccurs='0' name='value' type='xs:anyType'/>
	            				</xs:sequence>
	           				</xs:complexType>
	          			</xs:element>
	         		</xs:sequence>
	        	</xs:complexType>
	       </xs:element>
			
			<xs:complexType name='purgeResponse'>
				<xs:sequence />
			</xs:complexType>
		 */
		
		try 
		{
			// <xsd:element xmlns="" name="purgeRequest" type="qman:purgeRequest"/>
			
			Element methodRequestElement= _document.createElement("xsd:element");		
			String methodNameRequest = operationMetadata.getName()+"Request";
			methodRequestElement.setAttribute("name", methodNameRequest);
			methodRequestElement.setAttribute("type", "qman:"+methodNameRequest);
			
			// <xs:element name='purgeResponse' type='qman:purgeResponse' />
//			Element methodResponseElement= _document.createElement("xsd:element");		
			String methodNameResponse= operationMetadata.getName()+"Response";
//			methodResponseElement.setAttribute("name", methodNameResponse);
//			methodResponseElement.setAttribute("type", "qman:result");//+methodNameResponse);
			
			schema.appendChild(methodRequestElement);
//			schema.appendChild(methodResponseElement);
	
			/*
				<xs:complexType name='purgeRequest'>
					<xs:sequence>
						<xs:element name='arg0' type='xs:int' />
						<xs:element minOccurs='0' name='arg1' type='qman:hashMap' />
					</xs:sequence>
				</xs:complexType>
	
			 */
			
			Element methodNameRequestComplexType =  _document.createElement("xsd:complexType");
			methodNameRequestComplexType.setAttribute("name", methodNameRequest);
			Element methodNameRequestComplexTypeSequence = _document.createElement("xsd:sequence");
			
			for(MBeanParameterInfo parameter : operationMetadata.getSignature())
			{
				methodNameRequestComplexTypeSequence.appendChild(defineSchemaFor(parameter.getType(), parameter.getName()));
			}
						
			methodNameRequestComplexType.appendChild(methodNameRequestComplexTypeSequence);
			schema.appendChild(methodNameRequestComplexType);
			
			/*
		<message name="purgeResponseMessage">
			<part element='qman:purgeResponse' name='purgeResponse'></part>
		</message>
		
		<message name='purgeRequestMessage'>
			<part element="qman:purgeRequest" name='purgeRequest'></part>
		</message>
			 */	
			Element definitions = (Element) XPathAPI.selectSingleNode(_document, "/wsdl:definitions");
			
			String requestMessageName = methodNameRequest+"Message";
			String responseMessageName = methodNameResponse+"Message";
			
			Element requestMessage = _document.createElement("message");
			requestMessage.setAttribute("name", requestMessageName);
			Element requestPart = _document.createElement("wsdl:part");
			requestPart.setAttribute("element", "qman:"+methodNameRequest);
			requestPart.setAttribute("name", methodNameRequest);
			requestMessage.appendChild(requestPart);
			
			Element responseMessage = _document.createElement("wsdl:message");
			responseMessage.setAttribute("name", responseMessageName);
			Element responsePart = _document.createElement("wsdl:part");
			responsePart.setAttribute("element", "qman:result");//+methodNameResponse);
			responsePart.setAttribute("name", methodNameResponse);
			responseMessage.appendChild(responsePart);
			
			definitions.appendChild(requestMessage);
			definitions.appendChild(responseMessage);
			
			
			/*
	<operation name='purge'>
			<input message="qman:purgeRequestMessage">
			</input>
			<output message='qman:purgeResponseMessage'>
			</output>
		</operation>		 
			 */
			Element portType = (Element) XPathAPI.selectSingleNode(_document, "/wsdl:definitions/wsdl:portType");
			Element operation = _document.createElement("wsdl:operation");
			operation.setAttribute("name", operationMetadata.getName());
			
			Element input = _document.createElement("wsdl:input");
			input.setAttribute("message", "qman:"+requestMessageName);
			input.setAttribute("name", methodNameRequest);
			input.setAttribute("wsa:action", Names.NAMESPACE_URI+"/"+operationMetadata.getName());
			
			//name="SetResourcePropertiesRequest" wsa:Action="http://docs.oasis-open.org/wsrf/rpw-2/SetResourceProperties/SetResourcePropertiesRequest"/>
			
			operation.appendChild(input);
			
			Element output = _document.createElement("wsdl:output");
			output.setAttribute("message", "qman:"+responseMessageName);
			output.setAttribute("name", methodNameResponse);
			output.setAttribute("wsa:action", Names.NAMESPACE_URI+"/"+methodNameResponse);
			
			operation.appendChild(output);		
			
			portType.appendChild(operation);
			
			/*
			<operation name='purge'>
				<soap:operation soapAction='purge' />
				<input>
					<soap:body use='literal' />
				</input>
				<output>
					<soap:body use='literal' />
				</output>
			</operation>
			 */
			Element binding = (Element) XPathAPI.selectSingleNode(_document, "/wsdl:definitions/wsdl:binding");
			Element bindingOperation = _document.createElement("wsdl:operation");
			bindingOperation.setAttribute("name", operationMetadata.getName());
			
			Element soapOperation = _document.createElement("wsdl-soap:operation");
			soapOperation.setAttribute("soapAction", Names.NAMESPACE_URI+"/"+operationMetadata.getName());
			
			Element bindingInput = _document.createElement("wsdl:input");
			Element bodyIn = _document.createElement("wsdl-soap:body");
			bodyIn.setAttribute("use", "literal");
			
			Element bindingOutput = _document.createElement("wsdl:output");
			Element bodyOut = _document.createElement("wsdl-soap:body");
			bodyOut.setAttribute("use", "literal");
			
			bindingOutput.appendChild(bodyOut);
			bindingInput.appendChild(bodyIn);
			
			bindingOperation.appendChild(soapOperation);
			bindingOperation.appendChild(bindingInput);
			bindingOperation.appendChild(bindingOutput);
			
			binding.appendChild(bindingOperation);
		} catch(Exception exception) 
		{
			throw new BuilderException(exception);
		}
	}

	/**
	 * Director callback : all attributes have been notified.
	 * Nothing to do here.
	 */
	public void endAttributes() 
	{
		// N.A.
	}

	/**
	 * Director callback : all operations have been notified.
	 * Nothing to do here.
	 */
	public void endOperations() 
	{
		// N.A.
	}

	/**
	 * Returns the WSDL built by this builder.
	 * 
	 * @return the WSDL built by this builder.
	 */
	public Document getWsdl() 
	{
		WsdlDebugger.debug(_objectName,_document);
		return _document;
	}

	/**
	 * Injects the application context environment 
	 * on this builder.
	 * 
	 * @param environment the application context environment.
	 */
	public void setEnvironment(Environment environment) 
	{
		this._environment = (WSDMAdapterEnvironment)environment;
	}
	
	/**
	 * Injects the path of the wsdl document.
	 * 
	 * @param wsdlPath the path of the wsdl document.
	 */
	public void setWsdlPath(String wsdlPath)
	{
		_document = WsdlUtils.createWSDL(_environment, wsdlPath, true);
	}
	
	/**
	 * Create a reference to the WSRP properties element. 
	 * 
	 * @throws BuilderException in case of XPath evaluation problem. 
	 */
	private void createWsrpPropertiesElement() throws BuilderException 
	{
		try
		{
			_wsrpProperties = (Element) XPathAPI.selectSingleNode(
					_document, 
					WSRP_PROPERTIES_XPATH);
		} catch (TransformerException exception)
		{
			LOGGER.error(Messages.QMAN_100040_UNABLE_TO_LOCATE_WSRP_PROPERTIES);
			throw new BuilderException(exception);
		}		
	}

	/**
	 * Creates a template element that will be used for array 
	 * type schema declaration(s). 
	 */
	private void createReusableArrayComplextType()
	{
		_arrayComplexType = XmlUtils.createElement(_document, XSD_COMPLEX_TYPE_QNAME);
		Element sequence = XmlUtils.createElement(_document, XSD_SEQUENCE_QNAME);
		_nestedArrayType = XmlUtils.createElement(_document, XSD_ELEMENT_QNAME);
		_nestedArrayType.setAttribute(NAME_ATTRIBUTE, "entry");
		sequence.appendChild(_nestedArrayType);
		_arrayComplexType.appendChild(sequence);
	}
	
	private void createSchemaElement() throws BuilderException
	{
		try 
		{
			schema = (Element) XPathAPI.selectSingleNode(
					_document.getDocumentElement(),
					QMAN_SCHEMA_XPATH);
		} catch(Exception exception)
		{
			LOGGER.error(
					exception,
					Messages.QMAN_100034_WSDL_SCHEMA_SECTION_NOT_FOUND);
			throw new BuilderException(exception);
		}		
	}
	
	/**
	 * The template WSDL contains a dummy URL as service location that 
	 * needs to be replaced with the real service address.
	 * 
	 * @throws BuilderException when replacement fails (XPath problem).
	 */
	private void replaceDummyServiceLocationOnWsdl() throws BuilderException
	{
		try 
		{
			Attr location = (Attr) XPathAPI.selectSingleNode(
					_document, 
					SERVICE_LOCATION_XPATH);
			
			StringBuilder builder = new StringBuilder("http://")
				.append(InetAddress.getLocalHost().getHostName())
				.append(':')
				.append(System.getProperty(Names.ADAPTER_PORT_PROPERTY_NAME,"8080"))
				.append('/')
				.append(_environment.getContextPath())
				.append('/')
				.append("services/QManWsResource");
			location.setValue(builder.toString());
		} catch(Exception exception)
		{
			LOGGER.error(
					exception,
					Messages.QMAN_100026_SOAP_ADDRESS_REPLACEMENT_FAILURE);
			throw new BuilderException(exception);
		}
	}	
}