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.JSONObject;
20  import net.sf.json.xml.XMLSerializer;
21  
22  public class JsonMediaTypeHandler implements MediaTypeHandler
23  {
24     public boolean canHandle( String contentType )
25     {
26        return contentType != null && contentType.contains( "javascript" );
27     }
28  
29     public String createXmlRepresentation( HttpResponse response )
30     {
31  
32        try
33        {
34           String content = response.getContentAsString();
35           if( !StringUtils.hasContent( content ) )
36              return null;
37  
38           JSONObject json = JSONObject.fromObject( content );
39           XMLSerializer serializer = new XMLSerializer();
40           serializer.setTypeHintsEnabled( false );
41           content = serializer.write( json );
42           content = XmlUtils.prettyPrintXml( content );
43  
44           return content;
45        }
46        catch( Throwable e )
47        {
48           e.printStackTrace();
49        }
50        return null;
51     }
52  }