简体   繁体   English

Spring REST Web服务| 更新XML并发送响应

[英]Spring REST Web Service | Update an XML and send it in response

I am working on a Spring Restful Web service wherein I am returning an xml file as a response. 我正在使用Spring Restful Web服务,其中我将返回一个xml文件作为响应。 This XML file is placed inside the main/resources folder of the MAVEN project build in eclipse. 该XML文件位于Eclipse中的MAVEN项目构建的main / resources文件夹中。 The service accepts certain parameters from the caller and based on those parameters, it should update the XML file. 该服务接受来自调用方的某些参数,并应基于这些参数更新XML文件。 This project is deployed as WAR in the production server. 该项目作为WAR部署在生产服务器中。 On my local project, I can see the xml file being updated but in the production server it is not. 在我的本地项目上,我可以看到xml文件正在更新,但是在生产服务器中却没有。 How can I get this working in the production server ? 如何在生产服务器中使用它?

Below is the code for controller accepting the incoming request 以下是控制器接受传入请求的代码

@RestController
public class HelloWorldRestController {

@Autowired
UserService userService; // Service which will do all data
                            // retrieval/manipulation work

@Autowired
DialogServiceXml dialogService;

// Returning an xml file in the response
@CrossOrigin(origins = "*")
@RequestMapping(value = "/getUpdatedDialog", method = RequestMethod.POST, produces = "application/xml")
public ResponseEntity<InputStreamResource> downloadXMLFile(@RequestBody Dialog dialog,
        UriComponentsBuilder ucBuilder) throws IOException {

    // Update the xml file named : "mor_dialog.xml"
    dialogService.updateXml(new StringBuilder(dialog.getClassName()), new StringBuilder(dialog.getResponse()));

    // Pick up the updated file from the classpath
    ClassPathResource xmlFile = null;
    try {
        xmlFile = new ClassPathResource("mor_dialog.xml");
    } catch (Exception exception) {
        exception.printStackTrace();
    }

    // Code to prevent caching so that always the latest version of the file
    // is being sent.
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Cache-Control", "no-cache, np-store, must-revalidate");
    httpHeaders.add("Pragma", "no-cache");
    httpHeaders.add("Expires", "0");
    //httpHeaders.add("Access-Control-Allow-Origin", "http://nlc-mor-furniture.mybluemix.net");

    return ResponseEntity.ok().headers(httpHeaders).contentLength(xmlFile.contentLength())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(xmlFile.getInputStream()));
   }
}

Below is the class that unmarshals the XML, updates it based on the input parameters, then marshals it back 下面是取消封送XML,根据输入参数对其进行更新然后封送回XML的类。

@Service("dialogService")
public class DialogServiceXml implements DialogServiceXmlImpl {

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void updateXml(StringBuilder className, StringBuilder response) {
    JAXBContext jaxbContext = null;
    ClassLoader classLoader = getClass().getClassLoader();
    try {
        jaxbContext = JAXBContext.newInstance("com.sau.watson.dialog.xsd.beans");

        Unmarshaller JAXBUnmarshaller = jaxbContext.createUnmarshaller();

        Marshaller JAXBMarshaller = jaxbContext.createMarshaller();
        JAXBMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        JAXBMarshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "WatsonDialogDocument_1.0.xsd");

        File mor_dialog = new File(classLoader.getResource("mor_dialog.xml").getFile());
        //File mor_dialog = new File(classLoader.getResource("../../mor_dialog.xml").getFile());

        mor_dialog.setWritable(true);
        //File mor_dialog_updated = new File(classLoader.getResource("mor_dialog_updated.xml").getFile());

        InputStream is = new FileInputStream(mor_dialog);

        JAXBElement dialog = (JAXBElement) JAXBUnmarshaller.unmarshal(is);
        is.close();

        //JAXBElement dialog = (JAXBElement) JAXBUnmarshaller.unmarshal(new FileInputStream("src/main/java/com/sau/watson/dialog/xml/mor_dialog.xml"));

        DialogType dialogType = (DialogType) dialog.getValue();
        // System.out.println(dialogType.toString());
        // System.out.println(dialogType);

        FlowType flowType = (FlowType) dialogType.getFlow();

        for (FolderNodeType folderNodeType : flowType.getFolder()) {
            // System.out.println(folderNodeType.getLabel());

            if (folderNodeType.getLabel().equalsIgnoreCase("Library")) {

                for (ChatflowNode libChatFlowNode : folderNodeType.getInputOrOutputOrDefault()) {
                    FolderNodeType libraryFolderNode = (FolderNodeType) libChatFlowNode;
                    // System.out.println(libraryFolderNode.getId());
                    // System.out.println(libraryFolderNode.getLabel());

                    StringBuilder classNameFromXml = new StringBuilder();

                    for (ChatflowNode node : libraryFolderNode.getInputOrOutputOrDefault()) {
                        InputNodeType inputNodeType = (InputNodeType) node;

                        // Getting the class. Class name are encapsulated
                        // inside the <grammar> node
                        /**
                         * <grammar> <item>Salesperson_Great</item>
                         * <item>Great</item> </grammar>
                         */
                        for (Object grammerTypeObj : inputNodeType.getActionOrScriptOrGrammar()) {
                            GrammarType grammarType = (GrammarType) grammerTypeObj;

                            // We are always getting the first item as it is
                            // assumed that there is only one class in each
                            // grammar node
                            classNameFromXml
                                    .append(grammarType.getItemOrSourceOrParam().get(0).getValue().toString());
                            System.out.println("Class Name is : " + className);
                        }

                        // We are always getting the first item as it is
                        // assumed that there is only one class in each
                        // grammar node
                        /*
                         * List<Object> grammarTypeObj =
                         * inputNodeType.getActionOrScriptOrGrammar();
                         * GrammarType grammarType = (GrammarType)
                         * grammarTypeObj;
                         * 
                         * String className =
                         * grammarType.getItemOrSourceOrParam().get(0).
                         * getValue().toString();
                         * 
                         * System.out.println("Class Name is : "+className);
                         */

                        if (!classNameFromXml.toString().equalsIgnoreCase(className.toString())) {
                            continue;
                        }

                        // Getting all the response items corresponding to
                        // this class
                        for (ChatflowNode outputNodeObj : inputNodeType.getInputOrOutputOrDefault()) {

                            OutputNodeType outputNode = (OutputNodeType) outputNodeObj;
                            for (Object promptTypeObj : outputNode.getActionOrScriptOrPrompt()) {

                                PromptType promptType = (PromptType) promptTypeObj;

                                List<Serializable> responseItemObjs = promptType.getContent();
                                for (Object responseItemObj : responseItemObjs) {

                                    /*
                                     * if (responseItemObj instanceof
                                     * String) {
                                     * System.out.println(((String)
                                     * responseItemObj).trim()); }
                                     */
                                    if (responseItemObj instanceof JAXBElement) {
                                        // System.out.println("JAXBElement
                                        // Instance");

                                        JAXBElement responseItem = (JAXBElement) responseItemObj;

                                        System.out.println("The old response is : " + responseItem.getValue().toString());
                                        responseItem.setValue(response.toString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        FileOutputStream os = new FileOutputStream(mor_dialog);

        JAXBMarshaller.marshal(dialog, os);             
        //os.flush();
        os.close();

        //JAXBMarshaller.marshal(dialog, new FileOutputStream("src/main/java/com/sau/watson/dialog/xml/mor_dialog.xml"));

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


}

The src/main/resources folder is only available on your development machine before maven builds the war file. src / main / resources文件夹仅在maven生成war文件之前在开发计算机上可用。 After building the war the resources are added to the war file from the root of the classpath. 建立战争之后,资源将从类路径的根目录添加到战争文件。 If you want to be updating the file then you probably want to access the file from the file system rather than from the classpath. 如果要更新文件,则可能要从文件系统而不是从类路径访问文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM