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.rest.support.handlers;
14  
15  import com.eviware.soapui.impl.rest.support.MediaTypeHandler;
16  import com.eviware.soapui.impl.wsdl.submit.transports.http.HttpResponse;
17  import com.eviware.soapui.support.StringUtils;
18  import com.eviware.soapui.support.xml.XmlUtils;
19  import net.sf.json.JSON;
20  import net.sf.json.JSONSerializer;
21  import net.sf.json.xml.XMLSerializer;
22  
23  public class JsonMediaTypeHandler implements MediaTypeHandler
24  {
25     public boolean canHandle( String contentType )
26     {
27        return couldBeJsonContent( contentType );
28     }
29  
30     public static boolean couldBeJsonContent( String contentType )
31     {
32        return contentType != null && ( contentType.contains( "javascript" ) || contentType.contains( "json" ) );
33     }
34  
35     public String createXmlRepresentation( HttpResponse response )
36     {
37        try
38        {
39           String content = response.getContentAsString().trim();
40           if( !StringUtils.hasContent( content ) )
41              return null;
42  
43           JSON json = JSONSerializer.toJSON( content );
44           XMLSerializer serializer = new XMLSerializer();
45           serializer.setTypeHintsEnabled( false );
46           content = serializer.write( json );
47           content = XmlUtils.prettyPrintXml( content );
48  
49           return content;
50        }
51        catch( Throwable e )
52        {
53           e.printStackTrace();
54        }
55        return null;
56     }
57  }