ChipServiceImpl implements ChipService { public BufferedImage crop(BufferedImage inputImage, int x, int y, int w, int h) throws ChipOutOfBoundsException { validateNotNull(inputImage, "inputImage"); if (w < 0 || h < 0) { throw new ChipOutOfBoundsException( String.format( "method arguments 'w', 'h' may not be less than 0. Values were %s and %s.", w, h)); } if (x > inputImage.getWidth() || y > inputImage.getHeight()) { throw new ChipOutOfBoundsException( String.format( "method arguments 'x' and 'y' may not be greater than the width and height of the supplied image." + "\n image width = %s, x = %s\n image height = %s, y = %s", inputImage.getWidth(), x, inputImage.getHeight(), y)); } if (x < 0) { x = 0; } if (y < 0) { y = 0; } if (x + w > inputImage.getWidth()) { w = inputImage.getWidth() - x; } if (y + h > inputImage.getHeight()) { h = inputImage.getHeight() - y; } try { lock.acquire(); BufferedImage subImage; try { subImage = inputImage.getSubimage(x, y, w, h); } finally { lock.release(); } return subImage; } catch (InterruptedException e) { LOGGER.debug("Interrupt received while doing image processing.", e); Thread.currentThread().interrupt(); } return null; } ChipServiceImpl();  ChipServiceImpl(Semaphore lock); @Override BufferedImage chip(
      BufferedImage inputImage, Polygon inputImagePolygon, Polygon chipPolygon); BufferedImage crop(BufferedImage inputImage, int x, int y, int w, int h);  }
@Test(expected = ChipOutOfBoundsException.class) public void testCropInvalidHeight() throws ChipOutOfBoundsException { chipService.crop(inputImage, 10, 10, 100, -1); }
@Test(expected = ChipOutOfBoundsException.class) public void testCropInvalidWidth() throws ChipOutOfBoundsException { chipService.crop(inputImage, 10, 10, -1, 100); }
@Test(expected = ChipOutOfBoundsException.class) public void testCropInvalidX() throws ChipOutOfBoundsException { chipService.crop(inputImage, 10_000, 10, -1, 100); }
@Test(expected = ChipOutOfBoundsException.class) public void testCropInvalidY() throws ChipOutOfBoundsException { chipService.crop(inputImage, 10, 10_000, 100, 100); }
@Test public void testCropNegativeOrigin() throws ChipOutOfBoundsException, InterruptedException { BufferedImage result = chipService.crop(inputImage, -100, -100, 100, 100); assertThat(result.getWidth(), is(100)); assertThat(result.getHeight(), is(100)); verify(lock).acquire(); verify(lock).release(); }
@Test public void testCropExtremeWidthHeight() throws ChipOutOfBoundsException, InterruptedException { BufferedImage result = chipService.crop(inputImage, 0, 0, 10_000, 10_000); assertThat(result.getWidth(), is(inputImage.getWidth())); assertThat(result.getHeight(), is(inputImage.getHeight())); verify(lock).acquire(); verify(lock).release(); }