View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2010 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.io.ByteArrayInputStream;
16  import java.io.PrintWriter;
17  import java.io.StringWriter;
18  
19  import org.apache.xmlbeans.XmlObject;
20  import org.w3c.dom.Document;
21  import org.w3c.tidy.Tidy;
22  
23  import com.eviware.soapui.impl.rest.support.MediaTypeHandler;
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 HtmlMediaTypeHandler implements MediaTypeHandler
29  {
30  	public boolean canHandle( String contentType )
31  	{
32  		return contentType != null && contentType.equals( "text/html" );
33  	}
34  
35  	public String createXmlRepresentation( HttpResponse response )
36  	{
37  		String content = response == null ? null : response.getContentAsString();
38  		if( !StringUtils.hasContent( content ) )
39  			return "<xml/>";
40  
41  		try
42  		{
43  			XmlObject.Factory.parse( new ByteArrayInputStream( content.getBytes() ) );
44  			return content;
45  		}
46  		catch( Exception e )
47  		{
48  			// fall through, this wasn't xml
49  		}
50  
51  		try
52  		{
53  
54  			Tidy tidy = new Tidy();
55  			tidy.setXmlOut( true );
56  			tidy.setShowWarnings( false );
57  			tidy.setErrout( new PrintWriter( new StringWriter() ) );
58  			// tidy.setQuiet(true);
59  			tidy.setNumEntities( true );
60  			tidy.setQuoteNbsp( true );
61  			tidy.setFixUri( false );
62  
63  			Document document = tidy.parseDOM( new ByteArrayInputStream( content.getBytes() ), null );
64  			StringWriter writer = new StringWriter();
65  			XmlUtils.serializePretty( document, writer );
66  			return writer.toString();
67  		}
68  		catch( Throwable e )
69  		{
70  			e.printStackTrace();
71  		}
72  		return null;
73  	}
74  }