1
2
3
4
5
6
7
8
9
10
11
12
13 package com.eviware.soapui.impl.wsdl.submit.filters;
14
15 import org.apache.log4j.Logger;
16 import org.apache.xmlbeans.XmlCursor;
17 import org.apache.xmlbeans.XmlObject;
18 import org.w3c.dom.Element;
19 import org.w3c.dom.NamedNodeMap;
20 import org.w3c.dom.Node;
21
22 import com.eviware.soapui.SoapUI;
23 import com.eviware.soapui.impl.wsdl.WsdlRequest;
24 import com.eviware.soapui.impl.wsdl.submit.RequestFilter;
25 import com.eviware.soapui.impl.wsdl.submit.transports.http.BaseHttpRequestTransport;
26 import com.eviware.soapui.model.iface.SubmitContext;
27 import com.eviware.soapui.support.xml.XmlUtils;
28
29 /***
30 * RequestFilter for removing empty elements/attributes
31 *
32 * @author Ole.Matzura
33 */
34
35 public class RemoveEmptyContentRequestFilter implements RequestFilter
36 {
37 @SuppressWarnings("unused")
38 private final static Logger log = Logger.getLogger(PropertyExpansionRequestFilter.class);
39
40 public void filterRequest(SubmitContext context, WsdlRequest wsdlRequest)
41 {
42 if( wsdlRequest != null && !wsdlRequest.isRemoveEmptyContent())
43 return;
44
45 String content = (String) context.getProperty( BaseHttpRequestTransport.REQUEST_CONTENT );
46 content = removeEmptyContent( content );
47 if( content != null )
48 context.setProperty( BaseHttpRequestTransport.REQUEST_CONTENT, content );
49 }
50
51 public static String removeEmptyContent( String content )
52 {
53 XmlCursor cursor = null;
54
55 try
56 {
57 XmlObject xmlObject = XmlObject.Factory.parse( content );
58 cursor = xmlObject.newCursor();
59
60 cursor.toNextToken();
61
62
63 cursor.toNextToken();
64 boolean removed = false;
65
66 while( !cursor.isEnddoc() )
67 {
68 if( cursor.isContainer() )
69 {
70 Element elm = ( Element ) cursor.getDomNode();
71 NamedNodeMap attributes = elm.getAttributes();
72 if( attributes != null && attributes.getLength() > 0 )
73 {
74 for( int c = 0; c < attributes.getLength(); c++ )
75 {
76 Node node = attributes.item( c );
77 if( node.getNodeValue() == null || node.getNodeValue().trim().length() == 0 )
78 {
79 cursor.removeAttribute( XmlUtils.getQName( node ) );
80 removed = true;
81 }
82 }
83 }
84
85 if( cursor.getTextValue() == null || cursor.getTextValue().trim().length() == 0 &&
86 XmlUtils.getFirstChildElement( elm ) == null )
87 {
88 if( cursor.removeXml())
89 {
90 removed = true;
91 }
92 }
93 }
94
95 cursor.toNextToken();
96 }
97
98 if( removed )
99 {
100 return xmlObject.xmlText();
101 }
102 }
103 catch( Exception e )
104 {
105 SoapUI.logError( e );
106 }
107 finally
108 {
109 if( cursor != null )
110 cursor.dispose();
111 }
112
113 return null;
114 }
115 }