View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2007 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.mockoperation.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.Action;
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.actions.iface.tools.support.AbstractToolsAction;
43  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ArgumentBuilder;
44  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ProcessToolRunner;
45  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.RunnerContext;
46  import com.eviware.soapui.impl.wsdl.actions.iface.tools.support.ToolHost;
47  import com.eviware.soapui.impl.wsdl.actions.iface.tools.wsi.WSIReportPanel;
48  import com.eviware.soapui.impl.wsdl.mock.WsdlMockRequest;
49  import com.eviware.soapui.impl.wsdl.mock.WsdlMockResponse;
50  import com.eviware.soapui.model.mock.MockService;
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 WSIValidateResponseAction extends AbstractToolsAction<WsdlMockResponse>
64  {
65  	private String configFile;
66  	private File logFile;
67  
68  	public WSIValidateResponseAction(WsdlMockResponse request )
69  	{
70  		super( request, "Check WS-I Compliance", "Validates the current request/response againt the WS-I Basic Profile" );
71  		putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "alt W" ));
72  		
73  		setEnabled( request != null && request.getMockResult() != null );
74  	}
75  
76  	protected void generate(StringToStringMap values, ToolHost toolHost) throws Exception
77  	{
78  		if( modelItem.getMockResult() == null )
79  		{
80  			UISupport.showErrorMessage( "Request/Response required for WS-I validations" );
81  			return;
82  		}
83  		
84  		String wsiDir = SoapUI.getSettings().getString( WSISettings.WSI_LOCATION, null );
85  		if( wsiDir == null )
86  		{
87  			UISupport.showErrorMessage( "WSI Test Tools directory must be set in global preferences" );
88  			return;
89  		}
90  		
91  		if( modelItem.getAttachmentCount() > 0 )
92  		{
93  			if( !UISupport.confirm( "Response contains attachments which is not supported by " +
94  					"validation tools, validate anyway?", "Validation Warning" ))
95  				return;
96  		}
97  		
98  		ProcessBuilder builder = new ProcessBuilder();
99  		
100 		File reportFile = File.createTempFile( "wsi-report", ".xml" );
101 		
102 		ArgumentBuilder args = buildArgs( reportFile );
103 		builder.command(args.getArgs());
104 		builder.directory(new File(wsiDir + File.separatorChar + "java" + File.separatorChar + "bin" ));
105 		
106 		toolHost.run( new WSIProcessToolRunner( builder, reportFile ));
107 	}
108 
109 	private ArgumentBuilder buildArgs(File reportFile) throws Exception
110 	{
111 		File logFile = buildLog();
112 		File file = buildConfig(reportFile, logFile);
113 		Settings settings = modelItem.getSettings();
114 		
115 		ArgumentBuilder builder = new ArgumentBuilder( new StringToStringMap() );
116 		builder.startScript( "Analyzer", ".bat", ".sh" );
117 		
118 		builder.addArgs( "-config", file.getAbsolutePath() );
119 		
120 		// add this to command-line due to bug in wsi-tools (?)
121 		if( settings.getBoolean( WSISettings.ASSERTION_DESCRIPTION ))
122 			builder.addArgs( "-assertionDescription", "true" );
123 		
124 		return builder;
125 	}
126 
127 	private File buildLog() throws Exception
128 	{
129 		LogDocument logDoc = LogDocument.Factory.newInstance();
130 		Log log = logDoc.addNewLog();
131 		log.setTimestamp( Calendar.getInstance() );
132 		
133 		addMonitorConfig(log);
134 		addMessageConfig(log);
135 		
136 		logFile = File.createTempFile( "wsi-analyzer-log", ".xml" );
137 		logDoc.save( logFile );
138 		return logFile;
139 	}
140 
141 	private File buildConfig(File reportFile, File logFile) throws IOException
142 	{
143 		Settings settings = modelItem.getSettings();
144 		
145 		ConfigurationDocument configDoc = ConfigurationDocument.Factory.newInstance();
146 		Configuration config = configDoc.addNewConfiguration();
147 		
148 		config.setVerbose( settings.getBoolean( WSISettings.VERBOSE ) );
149 		AssertionResults results = config.addNewAssertionResults();
150 		results.setType( 
151 				AssertionResults.Type.Enum.forString( 
152 						settings.getString( WSISettings.RESULTS_TYPE, AssertionResults.Type.ONLY_FAILED.toString() )));
153 		
154 		results.setMessageEntry( settings.getBoolean( WSISettings.MESSAGE_ENTRY ) );
155 		results.setFailureMessage( settings.getBoolean( WSISettings.FAILURE_MESSAGE ) );
156 		results.setAssertionDescription( settings.getBoolean( WSISettings.ASSERTION_DESCRIPTION) );
157 
158 		ReportFile report = config.addNewReportFile();
159 		report.setLocation( reportFile.getAbsolutePath() );
160 		report.setReplace( true );
161 		
162 		AddStyleSheet stylesheet = report.addNewAddStyleSheet();
163 		stylesheet.setHref( ".//..//common//Profiles//SSBP10_BP11_TAD.xml" );
164 		stylesheet.setType( "text/xsl" );
165 		stylesheet.setAlternate( false );
166 		
167 		config.setTestAssertionsFile( "../../common/profiles/SSBP10_BP11_TAD.xml" );
168 
169 		LogFile logFileConfig = config.addNewLogFile();
170 		logFileConfig.setStringValue( logFile.getAbsolutePath() );
171 		logFileConfig.setCorrelationType( CorrelationType.ENDPOINT );
172 		
173 		/*
174 		WsdlInterface iface = (WsdlInterface) modelItem.getOperation().getInterface();
175 		
176 		WsdlReferenceConfig wsdlRef = config.addNewWsdlReference();
177 		wsdlRef.setWsdlURI( iface.getDefinition() );
178 		WsdlElementReferenceConfig wsdlElement = wsdlRef.addNewWsdlElement();
179 		wsdlElement.setType( WsdlElementTypeConfig.BINDING );
180 		wsdlElement.setStringValue( iface.getBindingName().getLocalPart() );
181 		wsdlElement.setNamespace( iface.getBindingName().getNamespaceURI() );
182 		wsdlRef.setServiceLocation( modelItem.getEndpoint() );
183 		*/
184 		
185 		configFile = configDoc.toString();
186 		
187 		File file = File.createTempFile( "wsi-analyzer-config", ".xml" );
188 		
189 		configDoc.save( file );
190 		return file;
191 	}
192 
193 	private void addMessageConfig(Log log) throws MalformedURLException
194 	{
195 		HttpMessageEntry requestMessage = HttpMessageEntry.Factory.newInstance();
196 		WsdlMockRequest mockRequest = modelItem.getMockResult().getMockRequest();
197 		requestMessage.addNewMessageContent().setStringValue( mockRequest.getRequestContent() );
198 		requestMessage.setConversationID( "1" );
199 		requestMessage.setTimestamp( Calendar.getInstance() );
200 		requestMessage.setID( "1" );
201 		MockService mockService = modelItem.getMockOperation().getMockService();
202 		URL endpoint = new URL( "http://127.0.0.1:" + mockService.getPort() + mockService.getPath() );
203 		requestMessage.setSenderHostAndPort( "localhost" );
204 		
205 		if( endpoint.getPort() > 0 )
206 			requestMessage.setReceiverHostAndPort( endpoint.getHost() + ":" + endpoint.getPort());
207 		else
208 			requestMessage.setReceiverHostAndPort( endpoint.getHost() );
209 
210 		requestMessage.setType( TcpMessageType.REQUEST );
211 		
212 		HttpMessageEntry responseMessage = HttpMessageEntry.Factory.newInstance();
213 		responseMessage.addNewMessageContent().setStringValue( modelItem.getMockResult().getResponseContent() );
214 		responseMessage.setConversationID( "1" );
215 		responseMessage.setType( TcpMessageType.RESPONSE );
216 		responseMessage.setTimestamp( Calendar.getInstance() );
217 		responseMessage.setID( "2" );
218 		responseMessage.setSenderHostAndPort( requestMessage.getReceiverHostAndPort() );
219 		responseMessage.setReceiverHostAndPort( requestMessage.getSenderHostAndPort() );
220 		
221 		String requestHeaders = buildHttpHeadersString( mockRequest.getRequestHeaders() );
222 		requestMessage.setHttpHeaders( "POST " + mockRequest.getPath() + " " + mockRequest.getProtocol() + "\r\n" + requestHeaders);
223 		
224 		responseMessage.setHttpHeaders( "HTTP/1.1 200 OK" + buildHttpHeadersString( modelItem.getMockResult().getResponseHeaders() ));
225 		
226 		log.setMessageEntryArray( new MessageEntry[] {requestMessage, responseMessage } );
227 	}
228 
229 	private void addMonitorConfig(Log log) throws Exception
230 	{
231 		Monitor monitor = log.addNewMonitor();
232 		
233 		monitor.setVersion( "1.5" );
234 		monitor.setReleaseDate( Calendar.getInstance() );
235 		
236 		org.wsI.testing.x2003.x03.monitorConfig.Configuration conf = monitor.addNewConfiguration();
237 		conf.setCleanupTimeoutSeconds( 0 );
238 		conf.setLogDuration( 0 );
239 		
240 		org.wsI.testing.x2003.x03.monitorConfig.LogFile logFileConf = conf.addNewLogFile();
241 		logFileConf.setLocation( "report.xml" );
242 		logFileConf.setReplace( true );
243 		
244 		/*
245 		ArrayOfRedirectConfig mintConf = conf.addNewManInTheMiddle();
246 		RedirectConfig redirect = mintConf.addNewRedirect();
247 		redirect.setListenPort( 9999 );
248 		redirect.setMaxConnections( 10 );
249 		redirect.setReadTimeoutSeconds( 10 );
250 		
251 		URL endpoint = new URL( modelItem.getEndpoint());
252 		if( endpoint.getPort() > 0 )
253 			redirect.setSchemeAndHostPort(  endpoint.getHost() + ":" + endpoint.getPort());
254 		else
255 			redirect.setSchemeAndHostPort(  endpoint.getHost() );
256 		*/
257 		
258 		Environment env = monitor.addNewEnvironment();
259 		NameVersionPair osConf = env.addNewOperatingSystem();
260 		osConf.setName( "Windows" );
261 		osConf.setVersion( "2003" );
262 		
263 		NameVersionPair rtConf = env.addNewRuntime();
264 		rtConf.setName( "java" );
265 		rtConf.setVersion( "1.5" );
266 		
267 		NameVersionPair xpConf = env.addNewXmlParser();
268 		xpConf.setName( "xmlbeans" );
269 		xpConf.setVersion( "2.2.0" );
270 		
271 		Implementation implConf = monitor.addNewImplementer();
272 		implConf.setName( "soapui" );
273 		implConf.setLocation( "here" );
274 	}
275 	
276 	private String buildHttpHeadersString(StringToStringMap requestHeaders)
277 	{
278 		StringBuffer buffer = new StringBuffer();
279 
280 		if( requestHeaders.containsKey( "#status#"))
281 		{
282 			buffer.append( requestHeaders.get( "#status#" )).append( "\r\n");
283 		}
284 		
285 		for( String header : requestHeaders.keySet() )
286 		{
287 			if( !header.equals( "#status#" ))
288 			   buffer.append( header ).append( ": ").append( requestHeaders.get( header )).append( "\r\n");
289 		}
290 		
291 		return buffer.toString();
292 	}
293 
294 	private class WSIProcessToolRunner extends ProcessToolRunner
295 	{
296 		private final File reportFile;
297 
298 		public WSIProcessToolRunner(ProcessBuilder builder, File reportFile )
299 		{
300 			super(builder, "WSI Message Validation", modelItem);
301 			this.reportFile = reportFile;
302 		}
303 		
304 		public String getDescription()
305 		{
306 			return "Running WSI Analysis tools..";
307 		}
308 
309 		protected void afterRun( int exitCode, RunnerContext context )
310 		{
311 			try
312 			{
313 				if( exitCode == 0 && context.getStatus() == RunnerContext.RunnerStatus.FINISHED )
314 				{
315 					WSIReportPanel panel = new WSIReportPanel( reportFile, configFile, logFile );
316 					panel.setPreferredSize( new Dimension( 600, 400 ));
317 					
318                UISupport.showDesktopPanel( 
319 							new DefaultDesktopPanel( "WS-I Report", "WS-I Report for validation of messages in MockResponse [" + modelItem.getName() + "]", panel ));
320 				}
321 			}
322 			catch( Exception e )
323 			{
324 				e.printStackTrace();
325 				UISupport.showErrorMessage( e );
326 			}
327 		}
328 		
329 		public boolean showLog()
330 		{
331 			return modelItem.getSettings().getBoolean( WSISettings.SHOW_LOG );
332 		}
333 	}
334 }