@Override public void actionPerformed(ActionEvent event) { JFileChooser fileChooser = new JFileChooser(); final FileNameExtensionFilter parameterFileFilter = createParameterFileFilter(); fileChooser.addChoosableFileFilter(parameterFileFilter); fileChooser.setFileFilter(parameterFileFilter); fileChooser.setDialogTitle(TITLE); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); applyCurrentDirectory(fileChooser); int response = fileChooser.showDialog(parentComponent, "Save"); if (JFileChooser.APPROVE_OPTION == response) { try { preserveCurrentDirectory(fileChooser); File selectedFile = fileChooser.getSelectedFile(); selectedFile = FileUtils.ensureExtension(selectedFile, "." + parameterFileFilter.getExtensions()[0]); DomElement domElement = parameterSupport.toDomElement(); escapeXmlElements(domElement); String xmlString = domElement.toXml(); writeToFile(xmlString, selectedFile); } catch (Exception e) { Debug.trace(e); Dialogs.showError(TITLE, "Could not load parameters.\n" + e.getMessage()); } } }
static void escapeXmlElements(DomElement domElement) { domElement.setValue(StringEscapeUtils.escapeXml(domElement.getValue())); String[] attributeNames = domElement.getAttributeNames(); for (String attributeName : attributeNames) { domElement.setAttribute(attributeName, StringEscapeUtils.escapeXml(domElement.getAttribute(attributeName))); } DomElement[] children = domElement.getChildren(); for (DomElement child : children) { escapeXmlElements(child); } }
@Test public void testEscapingXmlParameters() throws Exception { DefaultDomElement domElement = new DefaultDomElement("parameter"); String unescapedString = "12 < 13 && 56 > 42 & \"true\" + 'a name'"; String escapedString = "12 < 13 && 56 > 42 & "true" + 'a name'"; domElement.addChild(new DefaultDomElement("expression", unescapedString)); DefaultDomElement withAttribute = new DefaultDomElement("withAttribute"); withAttribute.setAttribute("attrib", unescapedString); domElement.addChild(withAttribute); OperatorMenu.escapeXmlElements(domElement); assertEquals(escapedString, domElement.getChild("expression").getValue()); assertEquals(escapedString, domElement.getChild("withAttribute").getAttribute("attrib")); String xmlString = domElement.toXml(); XppDom readDomElement = OperatorMenu.createDom(xmlString); assertEquals(unescapedString, readDomElement.getChild("expression").getValue()); assertEquals(unescapedString, readDomElement.getChild("withAttribute").getAttribute("attrib")); } }