Dattatray Satpute
Dattatray Satpute

Reputation: 263

Spring boot ResponseEntity not showing response in proper format if it cotains xml data as string

If response object contains the xml data in string format then it shows response in improper format.

  @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "Resource name not found"),
            @ApiResponse(responseCode = "415 ", description = "Unsupported Media Type"),
            @ApiResponse(responseCode = "500 ", description = "Application Error") })
    @GetMapping(value = "/validate-resource/{resourceName}", consumes = { MediaType.APPLICATION_JSON_VALUE,
            MediaType.APPLICATION_XML_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE,
                    MediaType.APPLICATION_XML_VALUE })
    public ResponseEntity<Response> connectionValidate(
            @Parameter(description = "resourceName cannot be empty.", required = true) @PathVariable(value = "resourceName", required = true) String resourceName)
            throws Throwable {
        HelperService helperService = new HelperService();
        if (resourceMap == null || resourceMap.get(resourceName) == null) {
            Response response = new Response();
            response.setStatus("error");
            response.setMessage("Resource name not found");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
        HashMap<String, String> resourceDataMap = resourceMap.get(resourceName);
        
        String localResponse = helperService.execute(helperSettingsFilePath,filepath, resourceDataMap, "SAP ERP",
                "validate-resource");
        
        
        Response response = new Response();
        response.setStatus("success");
        response.setData(localResponse);
        return new ResponseEntity<>(response, HttpStatus.OK);
    }   

When we call api it shows response in following format

<Response>
        <status>success</status>
        <message/>
        <data>
            &lt;?xml version="1.0" encoding="UTF-8"?>&#xd;
            &lt;Return>&#xd;
            &lt;Status name="SUCCESS">0&lt;/Status>&#xd;
            &lt;Description>Connection to the requested SapR3 Server was established successfully.&lt;/Description>&#xd;
            &lt;/Return>
        </data>
    </Response>

Expected out put

<Response>
<status>success</status>
<message/>
<data>
<?xml version="1.0" encoding="UTF-8"?>
<Return>
<Status name = "SUCCESS">0</Status>
<Description>Connection to the requested SapR3 Server was established successfully.</Description>
</Return>
</data>
</Response>

Please let me know what is going wrong here.

Upvotes: 1

Views: 1263

Answers (1)

Mahadev K
Mahadev K

Reputation: 350

I think the string should be formatted properly before sending. Convert String to Document and Document back to String and send it. You might need to add some dependency too I think.

Reference : https://www.journaldev.com/1237/java-convert-string-to-xml-document-and-xml-document-to-string

Sample code from reference


package com.journaldev.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class StringToDocumentToString {

    public static void main(String[] args) {
        final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                                "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                                "<role>Developer</role><gen>Male</gen></Emp>";
        Document doc = convertStringToDocument(xmlStr);
        
        String str = convertDocumentToString(doc);
        System.out.println(str);
    }

    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        
        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try  
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); 
            return doc;
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        return null;
    }

}

Mentioned output

<?xml version="1.0" encoding="UTF-8"?><Emp id="1"><name>Pankaj</name><age>25</age>
<role>Developer</role><gen>Male</gen></Emp>

Upvotes: 1

Related Questions