public void executeCommand(MojiCommand command) throws IOException { Tracker tracker = null; CommunicationException lastException = null; for (int attempt = 0; attempt < maxAttempts; attempt++) { try { tracker = trackerFactory.getTracker(); log.debug("executing {}", command); if (maxAttempts > 1) { log.debug("Attempt #{}", attempt); } command.executeWithTracker(tracker); return; } catch (CommunicationException e) { lastException = e; } finally { if (tracker != null) { tracker.close(); } } } if (maxAttempts > 1) { log.debug("All {} attempts failed", maxAttempts); } throw lastException; }
@Test public void everyThingClosesWithFirstTrackerFail() throws IOException { when(address.size()).thenReturn(2); when(mockTrackerFactory.getTracker()) .thenAnswer( new Answer<Tracker>() { boolean first = true; @Override public Tracker answer(InvocationOnMock invocation) throws Throwable { if (first) { first = false; throw new CommunicationException("Errror on communication"); } return mockTracker; } }); stream.write(1); stream.close(); verify(mockOutputStream).flush(); verify(mockOutputStream).close(); verify(mockHttpConnection).disconnect(); verify(mockTracker).createClose(KEY, DOMAIN, mockDestination, 1); verify(mockTracker).close(); verify(mockWriteLock).unlock(); }
@Before public void setUp() throws IOException { URL url = new URL("http://www.last.fm/"); when(mockDestination.getPath()).thenReturn(url); when(mockHttpFactory.newConnection(url)).thenReturn(mockHttpConnection); when(mockHttpConnection.getInputStream()).thenReturn(mockInputStream); when(mockHttpConnection.getOutputStream()).thenReturn(mockOutputStream); when(mockHttpConnection.getResponseMessage()).thenReturn("message"); when(mockHttpConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); when(mockTrackerFactory.getTracker()).thenReturn(mockTracker); when(address.size()).thenReturn(1); when(mockTrackerFactory.getAddresses()).thenReturn(address); stream = new FileUploadOutputStream( mockTrackerFactory, mockHttpFactory, KEY, DOMAIN, mockDestination, mockWriteLock); }
Executor(TrackerFactory trackerFactory) { this.trackerFactory = trackerFactory; maxAttempts = trackerFactory.getAddresses().size(); }