soapmock/src/main/java/com/gmgauthier/soapmock/controllers/MockController.java

74 lines
2.5 KiB
Java

package com.gmgauthier.soapmock.controllers;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.util.Objects;
@RestController
@RequestMapping(
consumes = MediaType.TEXT_XML_VALUE,
produces = MediaType.TEXT_XML_VALUE)
public class MockController {
@PostMapping(path ="/call1")
public String postCall1(@RequestBody String xmlRequestBody) throws Exception {
Document xmlRequest = parseRequestBody(xmlRequestBody);
Element root = xmlRequest.getDocumentElement();
NodeList nodeList = root.getChildNodes();
System.out.println(root.getNodeName());
for (int i = 0; i < nodeList.getLength(); i++){
System.out.println(nodeList.item(i).getNodeName());
System.out.println(nodeList.item(i).getNodeValue());
}
return getStaticResponse("soap-example.xml");
}
private String getStaticResponse(String fileName){
File file = null;
String content = null;
String filePath = "static/responses/" + fileName;
ClassLoader classLoader = getClass().getClassLoader();
try {
file = new File(
Objects.requireNonNull(classLoader
.getResource(filePath)).getFile());
} catch (NullPointerException e) {
e.printStackTrace();}
try {
assert file != null;
content = new String(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
e.printStackTrace();}
return content;
}
private Document parseRequestBody(String xmlRequestBody) throws Exception {
DocumentBuilderFactory dBfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dBfactory.newDocumentBuilder();
Document document =
builder.parse(new InputSource(new StringReader(xmlRequestBody)));
document.getDocumentElement().normalize();
return document;
}
}