View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2009 eviware.com 
3    *
4    *  soapUI is free software; you can redistribute it and/or modify it under the 
5    *  terms of version 2.1 of the GNU Lesser General Public License as published by 
6    *  the Free Software Foundation.
7    *
8    *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
9    *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
10   *  See the GNU Lesser General Public License for more details at gnu.org.
11   */
12  
13  package com.eviware.soapui.impl.wsdl.panels.request.actions;
14  
15  import java.awt.Dimension;
16  import java.io.File;
17  import java.io.IOException;
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  import java.util.Calendar;
21  
22  import javax.swing.SwingUtilities;
23  
24  import org.wsI.testing.x2003.x03.common.AddStyleSheet;
25  import org.wsI.testing.x2003.x03.log.Environment;
26  import org.wsI.testing.x2003.x03.log.HttpMessageEntry;
27  import org.wsI.testing.x2003.x03.log.Implementation;
28  import org.wsI.testing.x2003.x03.log.Log;
29  import org.wsI.testing.x2003.x03.log.LogDocument;
30  import org.wsI.testing.x2003.x03.log.MessageEntry;
31  import org.wsI.testing.x2003.x03.log.Monitor;
32  import org.wsI.testing.x2003.x03.log.NameVersionPair;
33  import org.wsI.testing.x2003.x03.log.TcpMessageType;
34  import org.wsI.testing.x2004.x07.analyzerConfig.AssertionResults;
35  import org.wsI.testing.x2004.x07.analyzerConfig.Configuration;
36  import org.wsI.testing.x2004.x07.analyzerConfig.ConfigurationDocument;
37  import org.wsI.testing.x2004.x07.analyzerConfig.LogFile;
38  import org.wsI.testing.x2004.x07.analyzerConfig.ReportFile;
39  import org.wsI.testing.x2004.x07.analyzerConfig.LogFile.CorrelationType;
40  
41  import com.eviware.soapui.SoapUI;
42  import com.eviware.soapui.impl.wsdl.WsdlRequest;
43  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.AbstractToolsAction;
44  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ArgumentBuilder;
45  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ProcessToolRunner;
46  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.RunnerContext;
47  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ToolHost;
48  import com.eviware.soapui.impl.wsdl.actions.iface.tools.wsi.WSIAnalyzeAction;
49  import com.eviware.soapui.impl.wsdl.actions.iface.tools.wsi.WSIReportPanel;
50  import com.eviware.soapui.model.iface.Response;
51  import com.eviware.soapui.model.settings.Settings;
52  import com.eviware.soapui.settings.WSISettings;
53  import com.eviware.soapui.support.UISupport;
54  import com.eviware.soapui.support.types.StringToStringMap;
55  import com.eviware.soapui.ui.support.DefaultDesktopPanel;
56  
57  /***
58   * Validates the request XML of a WsdlRequest
59   * 
60   * @author Ole.Matzura
61   */
62  
63  public class WSIValidateRequestAction extends AbstractToolsAction<WsdlRequest>
64  {
65  	private String configFile;
66  	private File logFile;
67  	private String wsiDir;
68  
69  	public WSIValidateRequestAction()
70  	{
71  		super( "Check WS-I Compliance", "Validates the current request/response againt the WS-I Basic Profile" );
72  	}
73  
74  	protected void generate( StringToStringMap values, ToolHost toolHost, WsdlRequest modelItem ) throws Exception
75  	{
76  		if( modelItem.getResponse() == null )
77  		{
78  			UISupport.showErrorMessage( "Response required for WS-I validations" );
79  			return;
80  		}
81  
82  		wsiDir = SoapUI.getSettings().getString( WSISettings.WSI_LOCATION,
83  				System.getProperty( "wsi.dir", System.getenv( "WSI_HOME" ) ) );
84  		if( wsiDir == null )
85  		{
86  			UISupport.showErrorMessage( "WSI Test Tools directory must be set in global preferences" );
87  			return;
88  		}
89  
90  		if( modelItem.getAttachmentCount() > 0 || modelItem.getResponse().getAttachments().length > 0 )
91  		{
92  			if( !UISupport.confirm( "Message contains attachments which is not supported by "
93  					+ "validation tools, validate anyway?", "Validation Warning" ) )
94  				return;
95  		}
96  
97  		ProcessBuilder builder = new ProcessBuilder();
98  
99  		File reportFile = File.createTempFile( "wsi-report", ".xml" );
100 
101 		ArgumentBuilder args = buildArgs( reportFile, modelItem );
102 		builder.command( args.getArgs() );
103 		builder.directory( new File( wsiDir + File.separatorChar + "java" + File.separatorChar + "bin" ) );
104 
105 		toolHost.run( new WSIProcessToolRunner( builder, reportFile, modelItem ) );
106 	}
107 
108 	private ArgumentBuilder buildArgs( File reportFile, WsdlRequest modelItem ) throws Exception
109 	{
110 		File logFile = buildLog( modelItem );
111 		File file = buildConfig( reportFile, logFile, modelItem );
112 		Settings settings = modelItem.getSettings();
113 
114 		ArgumentBuilder builder = new ArgumentBuilder( new StringToStringMap() );
115 		builder.startScript( "Analyzer", ".bat", ".sh" );
116 
117 		builder.addArgs( "-config", file.getAbsolutePath() );
118 
119 		// add this to command-line due to bug in wsi-tools (?)
120 		if( settings.getBoolean( WSISettings.ASSERTION_DESCRIPTION ) )
121 			builder.addArgs( "-assertionDescription", "true" );
122 
123 		return builder;
124 	}
125 
126 	private File buildLog( WsdlRequest modelItem ) throws Exception
127 	{
128 		LogDocument logDoc = LogDocument.Factory.newInstance();
129 		Log log = logDoc.addNewLog();
130 		log.setTimestamp( Calendar.getInstance() );
131 
132 		addMonitorConfig( log );
133 		addMessageConfig( log, modelItem );
134 
135 		logFile = File.createTempFile( "wsi-analyzer-log", ".xml" );
136 		logDoc.save( logFile );
137 		return logFile;
138 	}
139 
140 	private File buildConfig( File reportFile, File logFile, WsdlRequest modelItem ) throws IOException
141 	{
142 		Settings settings = modelItem.getSettings();
143 
144 		ConfigurationDocument configDoc = ConfigurationDocument.Factory.newInstance();
145 		Configuration config = configDoc.addNewConfiguration();
146 
147 		config.setVerbose( settings.getBoolean( WSISettings.VERBOSE ) );
148 		AssertionResults results = config.addNewAssertionResults();
149 		results.setType( AssertionResults.Type.Enum.forString( settings.getString( WSISettings.RESULTS_TYPE,
150 				AssertionResults.Type.ONLY_FAILED.toString() ) ) );
151 
152 		results.setMessageEntry( settings.getBoolean( WSISettings.MESSAGE_ENTRY ) );
153 		results.setFailureMessage( settings.getBoolean( WSISettings.FAILURE_MESSAGE ) );
154 		results.setAssertionDescription( settings.getBoolean( WSISettings.ASSERTION_DESCRIPTION ) );
155 
156 		ReportFile report = config.addNewReportFile();
157 		report.setLocation( reportFile.getAbsolutePath() );
158 		report.setReplace( true );
159 
160 		AddStyleSheet stylesheet = report.addNewAddStyleSheet();
161 		stylesheet.setHref( ".//..//common//Profiles//SSBP10_BP11_TAD.xml" );
162 		stylesheet.setType( "text/xsl" );
163 		stylesheet.setAlternate( false );
164 
165 		config.setTestAssertionsFile( "../../common/profiles/SSBP10_BP11_TAD.xml" );
166 
167 		LogFile logFileConfig = config.addNewLogFile();
168 		logFileConfig.setStringValue( logFile.getAbsolutePath() );
169 		logFileConfig.setCorrelationType( CorrelationType.ENDPOINT );
170 
171 		/*
172 		 * WsdlInterface iface = (WsdlInterface)
173 		 * modelItem.getOperation().getInterface();
174 		 * 
175 		 * WsdlReferenceConfig wsdlRef = config.addNewWsdlReference();
176 		 * wsdlRef.setWsdlURI( iface.getWsdlDefinition() );
177 		 * WsdlElementReferenceConfig wsdlElement = wsdlRef.addNewWsdlElement();
178 		 * wsdlElement.setType( WsdlElementTypeConfig.BINDING );
179 		 * wsdlElement.setStringValue( iface.getBindingName().getLocalPart() );
180 		 * wsdlElement.setNamespace( iface.getBindingName().getNamespaceURI() );
181 		 * wsdlRef.setServiceLocation( modelItem.getEndpoint() );
182 		 */
183 
184 		configFile = configDoc.toString();
185 
186 		File file = File.createTempFile( "wsi-analyzer-config", ".xml" );
187 
188 		configDoc.save( file );
189 		return file;
190 	}
191 
192 	private void addMessageConfig( Log log, WsdlRequest modelItem ) throws MalformedURLException
193 	{
194 		HttpMessageEntry requestMessage = HttpMessageEntry.Factory.newInstance();
195 		requestMessage.addNewMessageContent().setStringValue( modelItem.getRequestContent() );
196 		requestMessage.setConversationID( "1" );
197 		requestMessage.setTimestamp( Calendar.getInstance() );
198 		requestMessage.setID( "1" );
199 		URL endpoint = new URL( modelItem.getEndpoint() );
200 		requestMessage.setSenderHostAndPort( "localhost" );
201 
202 		if( endpoint.getPort() > 0 )
203 			requestMessage.setReceiverHostAndPort( endpoint.getHost() + ":" + endpoint.getPort() );
204 		else
205 			requestMessage.setReceiverHostAndPort( endpoint.getHost() );
206 
207 		requestMessage.setType( TcpMessageType.REQUEST );
208 
209 		Response response = modelItem.getResponse();
210 		HttpMessageEntry responseMessage = HttpMessageEntry.Factory.newInstance();
211 		responseMessage.addNewMessageContent().setStringValue( response.getContentAsString() );
212 		responseMessage.setConversationID( "1" );
213 		responseMessage.setType( TcpMessageType.RESPONSE );
214 		responseMessage.setTimestamp( Calendar.getInstance() );
215 		responseMessage.setID( "2" );
216 		responseMessage.setSenderHostAndPort( requestMessage.getReceiverHostAndPort() );
217 		responseMessage.setReceiverHostAndPort( requestMessage.getSenderHostAndPort() );
218 
219 		String requestHeaders = buildHttpHeadersString( response.getRequestHeaders() );
220 		requestMessage.setHttpHeaders( "POST " + endpoint.getPath() + " HTTP/1.1\r\n" + requestHeaders );
221 
222 		responseMessage.setHttpHeaders( buildHttpHeadersString( response.getResponseHeaders() ) );
223 
224 		log.setMessageEntryArray( new MessageEntry[] { requestMessage, responseMessage } );
225 	}
226 
227 	private void addMonitorConfig( Log log ) throws Exception
228 	{
229 		Monitor monitor = log.addNewMonitor();
230 
231 		monitor.setVersion( "1.5" );
232 		monitor.setReleaseDate( Calendar.getInstance() );
233 
234 		org.wsI.testing.x2003.x03.monitorConfig.Configuration conf = monitor.addNewConfiguration();
235 		conf.setCleanupTimeoutSeconds( 0 );
236 		conf.setLogDuration( 0 );
237 
238 		org.wsI.testing.x2003.x03.monitorConfig.LogFile logFileConf = conf.addNewLogFile();
239 		logFileConf.setLocation( "report.xml" );
240 		logFileConf.setReplace( true );
241 
242 		/*
243 		 * ArrayOfRedirectConfig mintConf = conf.addNewManInTheMiddle();
244 		 * RedirectConfig redirect = mintConf.addNewRedirect();
245 		 * redirect.setListenPort( 9999 ); redirect.setMaxConnections( 10 );
246 		 * redirect.setReadTimeoutSeconds( 10 );
247 		 * 
248 		 * URL endpoint = new URL( modelItem.getEndpoint()); if(
249 		 * endpoint.getPort() > 0 ) redirect.setSchemeAndHostPort(
250 		 * endpoint.getHost() + ":" + endpoint.getPort()); else
251 		 * redirect.setSchemeAndHostPort( endpoint.getHost() );
252 		 */
253 
254 		Environment env = monitor.addNewEnvironment();
255 		NameVersionPair osConf = env.addNewOperatingSystem();
256 		osConf.setName( "Windows" );
257 		osConf.setVersion( "2003" );
258 
259 		NameVersionPair rtConf = env.addNewRuntime();
260 		rtConf.setName( "java" );
261 		rtConf.setVersion( "1.5" );
262 
263 		NameVersionPair xpConf = env.addNewXmlParser();
264 		xpConf.setName( "xmlbeans" );
265 		xpConf.setVersion( "2.1.0" );
266 
267 		Implementation implConf = monitor.addNewImplementer();
268 		implConf.setName( "soapui" );
269 		implConf.setLocation( "here" );
270 	}
271 
272 	private String buildHttpHeadersString( StringToStringMap requestHeaders )
273 	{
274 		StringBuffer buffer = new StringBuffer();
275 
276 		if( requestHeaders.containsKey( "#status#" ) )
277 		{
278 			buffer.append( requestHeaders.get( "#status#" ) ).append( "\r\n" );
279 		}
280 
281 		for( String header : requestHeaders.keySet() )
282 		{
283 			if( !header.equals( "#status#" ) )
284 				buffer.append( header ).append( ": " ).append( requestHeaders.get( header ) ).append( "\r\n" );
285 		}
286 
287 		return buffer.toString();
288 	}
289 
290 	private class WSIProcessToolRunner extends ProcessToolRunner
291 	{
292 		private final File reportFile;
293 		private final WsdlRequest modelItem;
294 
295 		public WSIProcessToolRunner( ProcessBuilder builder, File reportFile, WsdlRequest modelItem )
296 		{
297 			super( builder, "WSI Message Validation", modelItem );
298 			this.reportFile = reportFile;
299 			this.modelItem = modelItem;
300 		}
301 
302 		public String getDescription()
303 		{
304 			return "Running WSI Analysis tools..";
305 		}
306 
307 		protected void afterRun( int exitCode, RunnerContext context )
308 		{
309 			if( exitCode == 0 && context.getStatus() == RunnerContext.RunnerStatus.FINISHED )
310 			{
311 				SwingUtilities.invokeLater( new Runnable()
312 				{
313 
314 					public void run()
315 					{
316 						try
317 						{
318 							WSIReportPanel panel = new WSIReportPanel( WSIAnalyzeAction.transformReport( reportFile ),
319 									configFile, logFile, true );
320 							panel.setPreferredSize( new Dimension( 600, 400 ) );
321 
322 							UISupport.showDesktopPanel( new DefaultDesktopPanel( "WS-I Report",
323 									"WS-I Report for validation of messages in request [" + modelItem.getName() + "]", panel ) );
324 						}
325 						catch( Exception e )
326 						{
327 							UISupport.showErrorMessage( e );
328 						}
329 					}
330 				} );
331 			}
332 		}
333 
334 		public boolean showLog()
335 		{
336 			return modelItem.getSettings().getBoolean( WSISettings.SHOW_LOG );
337 		}
338 
339 		@Override
340 		protected void beforeProcess( ProcessBuilder processBuilder, RunnerContext context )
341 		{
342 			processBuilder.environment().put( "WSI_HOME", wsiDir );
343 		}
344 	}
345 }