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.rest.support.handlers;
14  
15  import java.net.URL;
16  
17  import net.sf.json.JSON;
18  import net.sf.json.JSONException;
19  import net.sf.json.JSONSerializer;
20  import net.sf.json.xml.XMLSerializer;
21  
22  import com.eviware.soapui.impl.rest.support.MediaTypeHandler;
23  import com.eviware.soapui.impl.support.HttpUtils;
24  import com.eviware.soapui.impl.wsdl.submit.transports.http.HttpResponse;
25  import com.eviware.soapui.support.StringUtils;
26  import com.eviware.soapui.support.xml.XmlUtils;
27  
28  public class JsonMediaTypeHandler implements MediaTypeHandler
29  {
30  	public boolean canHandle( String contentType )
31  	{
32  		return couldBeJsonContent( contentType );
33  	}
34  
35  	public static boolean couldBeJsonContent( String contentType )
36  	{
37  		return contentType != null && ( contentType.contains( "javascript" ) || contentType.contains( "json" ) );
38  	}
39  
40  	public String createXmlRepresentation( HttpResponse response )
41  	{
42  		try
43  		{
44  			String content = response.getContentAsString().trim();
45  			if( !StringUtils.hasContent( content ) )
46  				return null;
47  
48  			JSON json = JSONSerializer.toJSON( content );
49  			XMLSerializer serializer = new XMLSerializer();
50  			serializer.setTypeHintsEnabled( false );
51  			serializer.setRootName( HttpUtils.isErrorStatus( response.getStatusCode() ) ? "Fault" : "Response" );
52  			URL url = response.getURL();
53  			serializer.setNamespace( "", url.getProtocol() + "://" + url.getHost() + url.getPath() );
54  			content = serializer.write( json );
55  			content = XmlUtils.prettyPrintXml( content );
56  
57  			return content;
58  		}
59  		catch( Throwable e )
60  		{
61  			if( !( e instanceof JSONException ) )
62  				e.printStackTrace();
63  		}
64  		return "<xml/>";
65  	}
66  }