ContextFileWorker { protected static void populateDocumentIfNecessary(final Document document) { Element root = document.getDocumentElement(); if (root == null) { root = document.createElement(ROOT_TAG); document.appendChild(root); } try { final String expression = "/" + ROOT_TAG + "/" + RECENT_PRESENTATIONS_TAG + "[1]"; Node recentPresentationsNode = (Node) xpath().evaluate(expression, root, NODE); if (recentPresentationsNode == null) { recentPresentationsNode = document.createElement(RECENT_PRESENTATIONS_TAG); root.appendChild(recentPresentationsNode); } } catch (XPathExpressionException e) { LOGGER.log(Level.WARNING, "Can not parse the document properly", e); } } private  ContextFileWorker(); static Set<RecentPresentation> readRecentPresentationFromFile(final File contextFile); static void saveRecentPresentationToFile(final File contextFile, final RecentPresentation recentPresentation); static void updateRecentPresentationInFile(final File contextFile, final RecentPresentation recentPresentation); static boolean recentPresentationAlreadyPresent(final File contextFile, final RecentPresentation recentPresentation); static Set<RecentPresentation> purgeRecentPresentations(final InputStream input, final OutputStream output, final long numberOfRecentPresentationsToKeep);  }
@Test public void populateEmptyDocument() throws Exception { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); ContextFileWorker.populateDocumentIfNecessary(document); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); assertNotNull(document.getDocumentElement()); assertEquals(ROOT_TAG, document.getDocumentElement().getTagName()); final Node recentPresentationsNode = (Node) xPath.evaluate("/" + ROOT_TAG + "/" + RECENT_PRESENTATIONS_TAG, document.getDocumentElement(), NODE); assertNotNull(recentPresentationsNode); }
@Test public void populateDocumentWhenNoRecentPresentationsTag() throws Exception { final String xml = "<slideshowfx></slideshowfx>"; final Document document = createDocumentFromString(xml); ContextFileWorker.populateDocumentIfNecessary(document); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); final Node recentPresentationsNode = (Node) xPath.evaluate("/" + ROOT_TAG + "/" + RECENT_PRESENTATIONS_TAG, document.getDocumentElement(), NODE); assertNotNull(recentPresentationsNode); }