1
2
3
4
5
6
7
8
9
10
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 }