ImageEmbedder implements Embedder { @Override public final void embed(final Book book, final URL url) throws IOException { Objects.requireNonNull(book); Objects.requireNonNull(url); byte[] fileContent; try(InputStream in = url.openStream()) { DigestInputStream dis = new DigestInputStream(in, messageDigest); fileContent = IOUtils.toByteArray(dis); } String fileName = getFileName(new String(Hex.encodeHex(messageDigest.digest())), url); Resource imgResource = new Resource( null, fileContent, fileName, MediatypeService.determineMediaType(FilenameUtils.getName(url.toString()))); book.addResource(imgResource); messageDigest.reset(); } ImageEmbedder(final MessageDigest messageDigest); @Override final String getHref(final URL url); @Override final void embed(final Book book, final URL url);  }
@Test(expected = NullPointerException.class) public void embed_NullBook_ThrowsNullPointerException() throws Exception { embedder.embed(null, new URL("file:/img/doesnotexist.png")); }
@Test(expected = NullPointerException.class) public void embed_NullUrl_ThrowsNullPointerException() throws Exception { embedder.embed(null, new URL("file:/img/doesnotexist.png")); }
@Test public void embed_EmbedPngGifJpgSvg_ResourcesAreEmbedded() throws Exception { Book book = new Book(); embedder.embed(book, getClass().getResource("/embed/image.jpg").toURI().toURL()); embedder.embed(book, getClass().getResource("/embed/image.jpeg").toURI().toURL()); embedder.embed(book, getClass().getResource("/embed/image.png").toURI().toURL()); embedder.embed(book, getClass().getResource("/embed/image.gif").toURI().toURL()); embedder.embed(book, getClass().getResource("/embed/image.svg").toURI().toURL()); Resources resources = book.getResources(); List<Resource> jpgs = resources.getResourcesByMediaType(MediatypeService.JPG); assertResources(jpgs, 2); List<Resource> pngs = resources.getResourcesByMediaType(MediatypeService.PNG); assertResources(pngs, 1); List<Resource> gifs = resources.getResourcesByMediaType(MediatypeService.GIF); assertResources(gifs, 1); List<Resource> svgs = resources.getResourcesByMediaType(MediatypeService.SVG); assertResources(svgs, 1); }
@Test public void embed_EmbedUnsupportedMediaType_ResourceIsEmbeddedAnyway() throws Exception { Book book = new Book(); embedder.embed(book, getClass().getResource("/embed/image.bmp").toURI().toURL()); assertEquals(1, book.getResources().size()); }
@Test(expected = IOException.class) public void embed_UrlDoesNotExist_ThrowsException() throws Exception { Book book = new Book(); embedder.embed(book, new URL("file:/does/not/exist")); }