<s> import json <EOL> import xml . dom . minidom <EOL> from StringIO import StringIO <EOL> class Formatter ( object ) : <EOL> def __init__ ( self , args = None ) : <EOL> self . args = args <EOL> def format ( text ) : <EOL> pass <EOL> class JsonFormatter ( Formatter ) : <EOL> def __init__ ( self , args = None ) : <EOL> super ( JsonFormatter , self ) . __init__ ( args ) <EOL> def format ( self , text ) : <EOL> formatted = None <EOL> try : <EOL> o = json . loads ( text ) <EOL> formatted = json . dumps ( o , indent = <NUM_LIT:2> ) <EOL> except ( TypeError , ValueError ) : <EOL> formatted = text <EOL> return formatted <EOL> class XmlFormatter ( Formatter ) : <EOL> def __init__ ( self , args = None ) : <EOL> super ( XmlFormatter , self ) . __init__ ( args ) <EOL> def format_xml ( self , node , writer , indent = "<STR_LIT>" , addindent = "<STR_LIT>" , newl = "<STR_LIT>" ) : <EOL> if node . nodeType == xml . dom . minidom . Node . TEXT_NODE and node . data . strip ( ) == "<STR_LIT>" : <EOL> return <EOL> writer . write ( indent + "<STR_LIT:<>" + node . tagName ) <EOL> attrs = node . attributes <EOL> keys = sorted ( attrs . keys ( ) ) <EOL> for key in keys : <EOL> writer . write ( "<STR_LIT>" % key ) <EOL> writer . write ( attrs [ key ] . value ) <EOL> writer . write ( "<STR_LIT>" ) <EOL> if node . childNodes : <EOL> writer . write ( "<STR_LIT:>>" ) <EOL> if all ( map ( lambda n : n . nodeType == xml . dom . minidom . Node . TEXT_NODE , <EOL> node . childNodes ) ) : <EOL> for child in node . childNodes : <EOL> child . writexml ( writer , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> else : <EOL> writer . write ( newl ) <EOL> for child in node . childNodes : <EOL> self . format_xml ( child , writer , indent + addindent , <EOL> addindent , newl ) <EOL> writer . write ( indent ) <EOL> writer . write ( "<STR_LIT>" % ( node . tagName , newl ) ) <EOL> else : <EOL> writer . write ( "<STR_LIT>" % ( newl ) ) <EOL> def format ( self , text ) : <EOL> formatted = None <EOL> try : <EOL> x = xml . dom . minidom . parseString ( text ) <EOL> writer = StringIO ( ) <EOL> self . format_xml ( x . childNodes [ <NUM_LIT:0> ] , writer , addindent = "<STR_LIT:U+0020>" , newl = "<STR_LIT:\n>" ) <EOL> formatted = writer . getvalue ( ) <EOL> x . unlink ( ) <EOL> except : <EOL> formatted = text <EOL> return formatted <EOL> JSONTYPES = ( <EOL> '<STR_LIT:application/json>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> XMLTYPES = ( <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' , <EOL> '<STR_LIT>' ) <EOL> def format_by_mimetype ( text , mimetype ) : <EOL> formatter = None <EOL> if mimetype in JSONTYPES : <EOL> formatter = JsonFormatter ( ) <EOL> elif mimetype in XMLTYPES : <EOL> formatter = XmlFormatter ( ) <EOL> if formatter : <EOL> return formatter . format ( text ) <EOL> else : <EOL> return text </s>
