### Question:
XmlParser { @SuppressWarnings("unchecked") public <T> T parse(String xmlPath, Class<T> clazz) throws EtiqetException { Schema schema = getSchema(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setSchema(schema); try { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); jaxbUnmarshaller.setSchema(schema); UnmarshallerHandler handler = jaxbUnmarshaller.getUnmarshallerHandler(); XMLReader reader = spf.newSAXParser().getXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new FileInputStream(new File(Environment.resolveEnvVars(xmlPath))))); return (T) handler.getResult(); } catch (ParserConfigurationException | SAXException | JAXBException e) { String error = String.format("Exception thrown while parsing %s as %s", xmlPath, clazz.getName()); LOG.error(error, e); throw new EtiqetException(error, e); } catch (IOException e) { String error = String.format("Exception thrown while trying to read %s", xmlPath); LOG.error(error, e); throw new EtiqetException(error, e); } }  @SuppressWarnings("unchecked") T parse(String xmlPath, Class<T> clazz); void validate(T instance, Class<?> source);  }### Answer:
@Test public void testParse() throws Exception { String configPath = "${etiqet.directory}/etiqet-core/src/test/resources/config/etiqet.config.xml"; XmlParser parser = new XmlParser(); Object genericResult = parser.parse(configPath, EtiqetConfiguration.class); assertNotNull(genericResult); assertTrue(genericResult instanceof EtiqetConfiguration); EtiqetConfiguration etiqetConfig = (EtiqetConfiguration) genericResult; assertEquals(2, etiqetConfig.getProtocols().size()); assertTrue(etiqetConfig.getProtocols().stream().anyMatch(p -> p.getName().equals("testProtocol"))); assertTrue(etiqetConfig.getProtocols().stream().anyMatch(p -> p.getName().equals("otherTestProtocol"))); assertEquals(2, etiqetConfig.getClients().size()); assertTrue(etiqetConfig.getClients().stream().anyMatch(c -> c.getName().equals("testClient1"))); assertTrue(etiqetConfig.getClients().stream().anyMatch(c -> c.getName().equals("testClient2"))); assertEquals(1, etiqetConfig.getServers().size()); assertTrue(etiqetConfig.getServers().stream().anyMatch(s -> s.getName().equals("testServer"))); }
@Test public void testParseBadProtocol() { String badSchemaFile = "file.not.found.xsd"; XmlParser parser = new XmlParser() { @Override protected String getSchemaFile() { return badSchemaFile; } }; try { parser.parse("file/not/relevant/for/test.xml", EtiqetConfiguration.class); fail("Using " + badSchemaFile + ", parsing should have thrown an EtiqetException"); } catch (Exception e) { assertTrue("Using " + badSchemaFile + ", parsing should have thrown an EtiqetException", e instanceof EtiqetException); assertEquals("Could not read " + badSchemaFile + ", please check your classpath configuration" , e.getMessage()); } }