View Javadoc

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