ace-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From j...@apache.org
Subject svn commit: r1522863 [2/2] - in /ace/trunk: org.apache.ace.agent.itest/src/org/apache/ace/agent/itest/ org.apache.ace.agent/src/org/apache/ace/agent/ org.apache.ace.agent/src/org/apache/ace/agent/impl/ org.apache.ace.agent/test/org/apache/ace/agent/impl/
Date Fri, 13 Sep 2013 10:54:34 GMT
Modified: ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandleImpl.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandleImpl.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandleImpl.java (original)
+++ ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandleImpl.java Fri
Sep 13 10:54:34 2013
@@ -20,11 +20,15 @@ package org.apache.ace.agent.impl;
 
 import java.io.File;
 import java.io.IOException;
+import java.net.HttpURLConnection;
 import java.net.URL;
-import java.util.List;
-import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 
+import org.apache.ace.agent.ConnectionHandler;
 import org.apache.ace.agent.DownloadHandle;
 import org.apache.ace.agent.DownloadResult;
 import org.apache.ace.agent.DownloadState;
@@ -34,23 +38,18 @@ import org.apache.ace.agent.DownloadStat
  * server supports this feature.
  */
 class DownloadHandleImpl implements DownloadHandle {
+    /**
+     * Size of the buffer used while downloading the content stream.
+     */
+    private static final int DEFAULT_READBUFFER_SIZE = 1024;
 
     private final DownloadHandlerImpl m_handler;
     private final URL m_url;
     private final int m_readBufferSize;
 
-    private volatile boolean m_started = false;
-    private volatile boolean m_completed = false;
-
     private volatile Future<Void> m_future;
-    private volatile DownloadCallableImpl m_callable;
     private volatile File m_file;
 
-    private volatile ProgressListener m_progressListener;
-    private volatile ResultListener m_completionListener;
-
-    private volatile DownloadResult m_downloadResult;
-
     DownloadHandleImpl(DownloadHandlerImpl handler, URL url) {
         this(handler, url, DEFAULT_READBUFFER_SIZE);
     }
@@ -62,137 +61,90 @@ class DownloadHandleImpl implements Down
     }
 
     @Override
-    public DownloadHandle setProgressListener(ProgressListener listener) {
-        m_progressListener = listener;
-        return this;
-    }
-
-    @Override
-    public DownloadHandle setCompletionListener(ResultListener listener) {
-        m_completionListener = listener;
-        return this;
+    public void discard() {
+        try {
+            stop();
+        }
+        finally {
+            m_file.delete();
+        }
     }
 
     @Override
-    public DownloadHandle start() {
-        return start(-1);
-    }
+    public void start(DownloadProgressListener listener) {
+        if (listener == null) {
+            throw new IllegalArgumentException("Listener cannot be null!");
+        }
 
-    DownloadHandle start(int failAtPosition) {
-        if (m_started) {
-            throw new IllegalStateException("Can not call start on a handle that is already
started");
+        if (m_future != null && !m_future.isDone()) {
+            throw new IllegalStateException("Can not call start on a handle that is already
started!");
         }
+
         if (m_file == null) {
             try {
-                m_file = File.createTempFile("download", ".bin");
+                m_file = File.createTempFile("download", ".bin", m_handler.getDataLocation());
             }
             catch (IOException e) {
-                failedCallback(0, null, e);
+                listener.completed(new DownloadResultImpl(DownloadState.FAILED, e, -1));
             }
         }
-        startDownload(failAtPosition);
-        return this;
-    }
 
-    @Override
-    public DownloadHandle stop() {
-        if (!m_started && !m_completed) {
-            throw new IllegalStateException("Can not call stop on a handle that is not yet
started");
-        }
-        m_started = false;
-        stopDownload();
-        return this;
+        m_future = getExecutor().submit(new DownloadCallableImpl(this, listener, m_file,
m_readBufferSize));
     }
 
     @Override
-    public DownloadResult result() {
-        if (m_completed)
-            return m_downloadResult;
-        if (!m_started)
-            throw new IllegalStateException("Can not call result on a handle that is not
yet started");
-        try {
-            m_future.get();
-        }
-        catch (Exception e) {
-            e.printStackTrace();
-        }
-        return m_downloadResult;
-    }
+    public DownloadResult startAndAwaitResult(long timeout, TimeUnit unit) throws InterruptedException
{
+        final CountDownLatch latch = new CountDownLatch(1);
+        final AtomicReference<DownloadResult> result = new AtomicReference<DownloadResult>();
 
-    @Override
-    public void discard() {
-        if (m_started)
-            stop();
-        m_file.delete();
-    }
-
-    void progressCallback(int statusCode, Map<String, List<String>> headers,
long contentLength, long progress) {
-        callProgressListener(m_progressListener, contentLength, progress);
-    }
+        start(new DownloadProgressListener() {
+            @Override
+            public void progress(long bytesRead, long totalBytes) {
+                // Nop
+            }
 
-    void successfulCallback(int statusCode, Map<String, List<String>> headers)
{
-        m_started = false;
-        m_completed = true;
-        m_downloadResult = new DownloadResultImpl(DownloadState.SUCCESSFUL, m_file, statusCode,
headers, null);
-        callCompletionListener(m_completionListener, m_downloadResult);
+            @Override
+            public void completed(DownloadResult downloadResult) {
+                result.set(downloadResult);
+                latch.countDown();
+            }
+        });
+        if (!latch.await(timeout, unit)) {
+            throw new InterruptedException("Failed to obtain result within given time constaints!");
+        }
+        return result.get();
     }
 
-    void stoppedCallback(int statusCode, Map<String, List<String>> headers, Throwable
cause) {
-        m_started = false;
-        m_completed = false;
-        m_downloadResult = new DownloadResultImpl(DownloadState.STOPPED, null, statusCode,
headers, cause);
-        callCompletionListener(m_completionListener, m_downloadResult);
-    }
+    @Override
+    public void stop() {
+        Future<Void> future = m_future;
+        if (future != null) {
+            if (future.isDone()) {
+                throw new IllegalStateException("Can not call stop on a handle that is not
yet started or completed!");
+            }
 
-    void failedCallback(int statusCode, Map<String, List<String>> headers, Throwable
cause) {
-        m_started = false;
-        m_completed = false;
-        m_downloadResult = new DownloadResultImpl(DownloadState.FAILED, null, statusCode,
headers, cause);
-        callCompletionListener(m_completionListener, m_downloadResult);
+            future.cancel(true /* mayInterruptIfRunning */);
+        }
+        m_future = null;
     }
 
-    void logDebug(String message, Object... args) {
+    final void logDebug(String message, Object... args) {
         m_handler.logDebug(message, args);
     }
 
-    void logInfo(String message, Object... args) {
-        m_handler.logInfo(message, args);
-    }
-
-    void logWarning(String message, Object... args) {
-        m_handler.logWarning(message, args);
+    final void logWarning(String message, Throwable cause, Object... args) {
+        m_handler.logWarning(message, cause, args);
     }
 
-    private void startDownload(int failAtPosition) {
-        m_started = true;
-        m_callable = new DownloadCallableImpl(this, m_url, m_file, m_readBufferSize, failAtPosition);
-        m_future = m_handler.getExecutor().submit(m_callable);
+    final HttpURLConnection openConnection() throws IOException {
+        return (HttpURLConnection) getConnectionHandler().getConnection(m_url);
     }
 
-    private void stopDownload() {
-        m_started = false;
-        m_callable.abort();
+    private ConnectionHandler getConnectionHandler() {
+        return m_handler.getConnectionHandler();
     }
 
-    private static void callProgressListener(ProgressListener listener, long contentLength,
long progress) {
-        if (listener != null) {
-            try {
-                listener.progress(contentLength, progress);
-            }
-            catch (Exception e) {
-                // ignore
-            }
-        }
-    }
-
-    private static void callCompletionListener(ResultListener listener, DownloadResult result)
{
-        if (listener != null && result != null) {
-            try {
-                listener.completed(result);
-            }
-            catch (Exception e) {
-                // ignore
-            }
-        }
+    private ExecutorService getExecutor() {
+        return m_handler.getExecutor();
     }
 }

Modified: ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandlerImpl.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandlerImpl.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandlerImpl.java
(original)
+++ ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadHandlerImpl.java
Fri Sep 13 10:54:34 2013
@@ -18,6 +18,7 @@
  */
 package org.apache.ace.agent.impl;
 
+import java.io.File;
 import java.net.URL;
 import java.util.concurrent.ExecutorService;
 
@@ -25,9 +26,19 @@ import org.apache.ace.agent.DownloadHand
 import org.apache.ace.agent.DownloadHandler;
 
 public class DownloadHandlerImpl extends ComponentBase implements DownloadHandler {
+    private final File m_dataLocation;
 
-    public DownloadHandlerImpl() {
+    public DownloadHandlerImpl(File dataLocation) {
         super("downloads");
+
+        m_dataLocation = dataLocation;
+    }
+
+    /**
+     * @return the location to (temporarily) store data.
+     */
+    public File getDataLocation() {
+        return m_dataLocation;
     }
 
     @Override

Modified: ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadResultImpl.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadResultImpl.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadResultImpl.java (original)
+++ ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/DownloadResultImpl.java Fri
Sep 13 10:54:34 2013
@@ -22,26 +22,28 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.util.List;
-import java.util.Map;
 
 import org.apache.ace.agent.DownloadResult;
 import org.apache.ace.agent.DownloadState;
 
 public class DownloadResultImpl implements DownloadResult {
+    private final DownloadState m_state;
+    private final File m_file;
+    private final int m_code;
+    private final Throwable m_cause;
 
-    final DownloadState m_state;
-    final File m_file;
-    final int m_code;
-    final Map<String, List<String>> m_headers;
-    final Throwable m_cause;
+    DownloadResultImpl(DownloadState state, Throwable cause, int code) {
+        m_state = state;
+        m_file = null;
+        m_code = code;
+        m_cause = cause;
+    }
 
-    DownloadResultImpl(DownloadState state, File file, int code, Map<String, List<String>>
headers, Throwable cause) {
+    DownloadResultImpl(DownloadState state, File file, int code) {
         m_state = state;
         m_file = file;
         m_code = code;
-        m_headers = headers;
-        m_cause = cause;
+        m_cause = null;
     }
 
     @Override
@@ -61,11 +63,6 @@ public class DownloadResultImpl implemen
     }
 
     @Override
-    public Map<String, List<String>> getHeaders() {
-        return m_headers;
-    }
-
-    @Override
     public Throwable getCause() {
         return m_cause;
     }

Modified: ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/InternalConstants.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/InternalConstants.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/InternalConstants.java (original)
+++ ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/InternalConstants.java Fri
Sep 13 10:54:34 2013
@@ -28,11 +28,12 @@ public interface InternalConstants {
      */
     String AGENT_CONFIG_CHANGED = "agent/config/CHANGED";
     /**
-     * Internal event topic used when a deployment is started.
+     * Internal event topic used when the installation of a deployment package or agent update
is started.
      */
-    String AGENT_DEPLOYMENT_INSTALL = "agent/deployment/INSTALL";
+    String AGENT_INSTALLATION_START = "agent/installation/START";
     /**
-     * Internal event topic used when a deployment is complete (either or not successful).
+     * Internal event topic used when the installation of a deployment package or agent update
is complete (either or
+     * not successful).
      */
-    String AGENT_DEPLOYMENT_COMPLETE = "agent/deployment/COMPLETE";
+    String AGENT_INSTALLATION_COMPLETE = "agent/installation/COMPLETE";
 }

Modified: ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/UpdateHandlerBase.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/UpdateHandlerBase.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/UpdateHandlerBase.java (original)
+++ ace/trunk/org.apache.ace.agent/src/org/apache/ace/agent/impl/UpdateHandlerBase.java Fri
Sep 13 10:54:34 2013
@@ -35,14 +35,30 @@ import java.util.TreeSet;
 import org.apache.ace.agent.AgentConstants;
 import org.apache.ace.agent.DownloadHandle;
 import org.apache.ace.agent.RetryAfterException;
+import org.apache.ace.agent.UpdateHandler;
 import org.osgi.framework.Version;
 
-public class UpdateHandlerBase extends ComponentBase {
+abstract class UpdateHandlerBase extends ComponentBase implements UpdateHandler {
 
     public UpdateHandlerBase(String componentIdentifier) {
         super(componentIdentifier);
     }
 
+    @Override
+    public final Version getHighestAvailableVersion() throws RetryAfterException, IOException
{
+        SortedSet<Version> available = new TreeSet<Version>();
+        try {
+            available = getAvailableVersions();
+        }
+        catch (IOException e) {
+            // Hopefully temporary problem due to remote IO or configuration. No cause to
abort the sync so we just
+            // log it as a warning.
+            logWarning("Exception while retrieving agent versions", e);
+        }
+
+        return getHighestVersion(available);
+    }
+
     protected SortedSet<Version> getAvailableVersions(URL endpoint) throws RetryAfterException,
IOException {
         SortedSet<Version> versions = new TreeSet<Version>();
         URLConnection connection = null;
@@ -79,15 +95,18 @@ public class UpdateHandlerBase extends C
         return getIdentificationHandler().getAgentId();
     }
 
-    protected InputStream getInputStream(URL packageURL) throws IOException {
-        URLConnection urlConnection = null;
+    protected InputStream getInputStream(URL packageURL) throws RetryAfterException, IOException
{
+        URLConnection connection = null;
         // TODO handle problems and retries
         try {
-            urlConnection = getConnection(packageURL);
-            return urlConnection.getInputStream();
+            connection = getConnection(packageURL);
+
+            checkConnectionResponse(connection);
+
+            return connection.getInputStream();
         }
         catch (IOException e) {
-            close(urlConnection);
+            close(connection);
             throw e;
         }
     }
@@ -130,4 +149,12 @@ public class UpdateHandlerBase extends C
     private URLConnection getConnection(URL url) throws IOException {
         return getConnectionHandler().getConnection(url);
     }
+
+    private Version getHighestVersion(SortedSet<Version> available) {
+        Version highest = Version.emptyVersion;
+        if (available != null && !available.isEmpty()) {
+            highest = available.last();
+        }
+        return highest;
+    }
 }

Modified: ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/CustomControllerTest.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/CustomControllerTest.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/CustomControllerTest.java
(original)
+++ ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/CustomControllerTest.java
Fri Sep 13 10:54:34 2013
@@ -21,7 +21,7 @@ package org.apache.ace.agent.impl;
 import static org.easymock.EasyMock.eq;
 import static org.easymock.EasyMock.expect;
 import static org.easymock.EasyMock.expectLastCall;
-import static org.easymock.EasyMock.notNull;
+import static org.easymock.EasyMock.*;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -29,6 +29,7 @@ import java.io.InputStream;
 import java.net.URL;
 import java.util.SortedSet;
 import java.util.TreeSet;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.ace.agent.AgentControl;
 import org.apache.ace.agent.DeploymentHandler;
@@ -77,7 +78,6 @@ public class CustomControllerTest extend
 
     @BeforeMethod
     public void setUpAgain() throws Exception {
-
         m_dummyInputStream = new FileInputStream(m_dummyFile);
 
         DownloadResult downloadResult = addTestMock(DownloadResult.class);
@@ -85,20 +85,19 @@ public class CustomControllerTest extend
         expect(downloadResult.getInputStream()).andReturn(m_dummyInputStream).anyTimes();
 
         DownloadHandle downloadHandle = addTestMock(DownloadHandle.class);
-        expect(downloadHandle.start()).andReturn(downloadHandle).anyTimes();
-        expect(downloadHandle.result()).andReturn(downloadResult).anyTimes();
+        expect(downloadHandle.startAndAwaitResult(anyLong(), notNull(TimeUnit.class))).andReturn(downloadResult).anyTimes();
 
         DeploymentHandler deploymentHandler = addTestMock(DeploymentHandler.class);
         expect(deploymentHandler.getInstalledVersion()).andReturn(m_version2).anyTimes();
         expect(deploymentHandler.getAvailableVersions()).andReturn(m_availableVersions).anyTimes();
         expect(deploymentHandler.getDownloadHandle(eq(m_version3), eq(true))).andReturn(downloadHandle).once();
-        deploymentHandler.deployPackage(notNull(InputStream.class));
+        deploymentHandler.install(notNull(InputStream.class));
         expectLastCall().once();
 
         m_agentContext = mockAgentContext();
         m_agentContext.setHandler(DeploymentHandler.class, deploymentHandler);
         replayTestMocks();
-        
+
         m_agentContext.start();
         m_agentControl = new AgentControlImpl(m_agentContext);
     }
@@ -112,19 +111,18 @@ public class CustomControllerTest extend
     }
 
     @Test
-    public void testDowlownloading() throws Exception {
-
+    public void testDownloading() throws Exception {
         Version current = m_agentControl.getDeploymentHandler().getInstalledVersion();
         Version highest = m_agentControl.getDeploymentHandler().getAvailableVersions().last();
-        if (highest.compareTo(current) > 0) {
 
+        if (highest.compareTo(current) > 0) {
             DownloadHandle handle = m_agentControl.getDeploymentHandler().getDownloadHandle(highest,
true);
-            DownloadResult result = handle.start().result();
+            DownloadResult result = handle.startAndAwaitResult(5, TimeUnit.SECONDS);
 
             if (result.getState() == DownloadState.SUCCESSFUL) {
                 InputStream inputStream = result.getInputStream();
                 try {
-                    m_agentControl.getDeploymentHandler().deployPackage(inputStream);
+                    m_agentControl.getDeploymentHandler().install(inputStream);
                 }
                 finally {
                     inputStream.close();

Modified: ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DeploymentHandlerImplTest.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DeploymentHandlerImplTest.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DeploymentHandlerImplTest.java
(original)
+++ ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DeploymentHandlerImplTest.java
Fri Sep 13 10:54:34 2013
@@ -210,7 +210,7 @@ public class DeploymentHandlerImplTest e
     @Test
     public void testPackageSize() throws Exception {
         DeploymentHandler deploymentHandler = m_agentContext.getHandler(DeploymentHandler.class);
-        long packageSize = deploymentHandler.getPackageSize(m_version1, true);
+        long packageSize = deploymentHandler.getSize(m_version1, true);
         assertEquals(packageSize, m_remotePackageSize);
     }
 
@@ -219,7 +219,7 @@ public class DeploymentHandlerImplTest e
         DeploymentHandler deploymentHandler = m_agentContext.getHandler(DeploymentHandler.class);
         InputStream inputStream = deploymentHandler.getInputStream(m_version3, true);
         try {
-            deploymentHandler.deployPackage(inputStream);
+            deploymentHandler.install(inputStream);
         }
         finally {
             inputStream.close();

Modified: ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DownloadHandlerTest.java
URL: http://svn.apache.org/viewvc/ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DownloadHandlerTest.java?rev=1522863&r1=1522862&r2=1522863&view=diff
==============================================================================
--- ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DownloadHandlerTest.java
(original)
+++ ace/trunk/org.apache.ace.agent/test/org/apache/ace/agent/impl/DownloadHandlerTest.java
Fri Sep 13 10:54:34 2013
@@ -21,7 +21,6 @@ package org.apache.ace.agent.impl;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertSame;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -32,11 +31,11 @@ import java.net.URL;
 import java.security.DigestInputStream;
 import java.security.DigestOutputStream;
 import java.security.MessageDigest;
-import java.util.ArrayList;
-import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
@@ -45,12 +44,14 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.ace.agent.AgentContext;
+import org.apache.ace.agent.ConnectionHandler;
 import org.apache.ace.agent.DownloadHandle;
-import org.apache.ace.agent.DownloadHandle.ProgressListener;
-import org.apache.ace.agent.DownloadHandle.ResultListener;
+import org.apache.ace.agent.DownloadHandle.DownloadProgressListener;
 import org.apache.ace.agent.DownloadHandler;
 import org.apache.ace.agent.DownloadResult;
 import org.apache.ace.agent.DownloadState;
+import org.apache.ace.agent.EventsHandler;
+import org.apache.ace.agent.LoggingHandler;
 import org.apache.ace.agent.testutil.BaseAgentTest;
 import org.apache.ace.agent.testutil.TestWebServer;
 import org.testng.annotations.AfterTest;
@@ -68,12 +69,14 @@ public class DownloadHandlerTest extends
         @Override
         public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException {
             String retry = req.getParameter("retry");
-            if (retry != null)
+            if (retry != null) {
                 ((HttpServletResponse) res).setHeader("Retry-After", retry);
+            }
             int code = 500;
             String status = req.getParameter("status");
-            if (status != null)
+            if (status != null) {
                 code = Integer.parseInt(status);
+            }
             ((HttpServletResponse) res).sendError(code, "You asked for it");
         }
     }
@@ -91,14 +94,16 @@ public class DownloadHandlerTest extends
 
     @BeforeTest
     public void setUpOnceAgain() throws Exception {
-
         int port = 8883;
 
         m_200url = new URL("http://localhost:" + port + "/testfile.txt");
         m_404url = new URL("http://localhost:" + port + "/error?status=404");
         m_503url = new URL("http://localhost:" + port + "/error?status=503&retry=500");
 
-        m_200file = new File(new File("generated"), "testfile.txt");
+        File dataLocation = new File("generated");
+
+        m_200file = new File(dataLocation, "testfile.txt");
+
         DigestOutputStream dos = new DigestOutputStream(new FileOutputStream(m_200file),
MessageDigest.getInstance("MD5"));
         for (int i = 0; i < 10000; i++) {
             dos.write(String.valueOf(System.currentTimeMillis()).getBytes());
@@ -114,9 +119,13 @@ public class DownloadHandlerTest extends
         m_agentContextImpl = mockAgentContext();
         m_agentContext = m_agentContextImpl;
 
-        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
+        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
+
         m_agentContextImpl.setHandler(ScheduledExecutorService.class, executorService);
-        m_agentContextImpl.setHandler(DownloadHandler.class, new DownloadHandlerImpl());
+        m_agentContextImpl.setHandler(EventsHandler.class, new EventsHandlerImpl(mockBundleContext()));
+        m_agentContextImpl.setHandler(ConnectionHandler.class, new ConnectionHandlerImpl());
+        m_agentContextImpl.setHandler(LoggingHandler.class, new LoggingHandlerImpl());
+        m_agentContextImpl.setHandler(DownloadHandler.class, new DownloadHandlerImpl(dataLocation));
 
         m_agentContextImpl.start();
         replayTestMocks();
@@ -132,95 +141,65 @@ public class DownloadHandlerTest extends
     @Test
     public void testSuccessful_noresume_result() throws Exception {
         DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
-        final DownloadHandle handle = downloadHandler.getHandle(m_200url).start();
-        final DownloadResult result = handle.result();
+
+        DownloadResult result = downloadHandler.getHandle(m_200url).startAndAwaitResult(10,
TimeUnit.SECONDS);
         assertSuccessFul(result, 200, m_200digest);
     }
 
     @Test
-    public void testSuccessful_noresume_listener() throws Exception {
+    public void testSuccessful_resume_result() throws Exception {
         DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
+
+        final AtomicReference<DownloadResult> resultRef = new AtomicReference<DownloadResult>();
         final CountDownLatch latch = new CountDownLatch(1);
-        final List<DownloadResult> holder = new ArrayList<DownloadResult>();
-        final DownloadHandle handle = downloadHandler.getHandle(m_200url)
-            .setCompletionListener(new ResultListener() {
-                @Override
-                public void completed(DownloadResult result) {
-                    holder.add(result);
-                    latch.countDown();
-                }
-            }).start();
-        latch.await();
-        assertSuccessFul(holder.get(0), 200, m_200digest);
-        assertSame(handle.result(), holder.get(0), "Await should return same result given
to the completion handler.");
-    }
 
-    @Test
-    public void testSuccessful_resume_result() throws Exception {
-        DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
         final DownloadHandle handle = downloadHandler.getHandle(m_200url);
-        handle.setProgressListener(new ProgressListener() {
+        handle.start(new DownloadProgressListener() {
             @Override
-            public void progress(long contentLength, long progress) {
+            public void progress(long read, long total) {
                 handle.stop();
             }
-        }).start();
-        assertStopped(handle.result(), 200);
-        assertStopped(handle.start().result(), 206);
-        assertSuccessFul(handle.setProgressListener(null).start().result(), 206, m_200digest);
-    }
 
-    @Test
-    public void testFailedIO_nostatus_result() throws Exception {
-        DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
-        DownloadHandle handle = downloadHandler.getHandle(m_200url, 2048);
+            @Override
+            public void completed(DownloadResult downloadResult) {
+                resultRef.set(downloadResult);
+                latch.countDown();
+            }
+        });
 
-        DownloadResult result = ((DownloadHandleImpl) handle).start(DownloadCallableImpl.FAIL_OPENCONNECTION).result();
-        assertFailed(result, 0);
-        assertNull(result.getHeaders());
-
-        result = ((DownloadHandleImpl) handle).start(DownloadCallableImpl.FAIL_OPENINPUTSTREAM).result();
-        assertFailed(result, 200);
-        assertNotNull(result.getHeaders());
-
-        result = ((DownloadHandleImpl) handle).start(DownloadCallableImpl.FAIL_OPENOUTPUTSTREAM).result();
-        assertFailed(result, 200);
-        assertNotNull(result.getHeaders());
-
-        result = ((DownloadHandleImpl) handle).start(DownloadCallableImpl.FAIL_AFTERFIRSTWRITE).result();
-        assertFailed(result, 200);
-        assertNotNull(result.getHeaders());
-
-        result = ((DownloadHandleImpl) handle).start(DownloadCallableImpl.FAIL_AFTERFIRSTWRITE).result();
-        assertFailed(result, 206);
-        assertNotNull(result.getHeaders());
+        latch.await(5, TimeUnit.SECONDS);
 
-        result = handle.start().result();
-        assertSuccessFul(result, 206, m_200digest);
+        DownloadResult result = resultRef.get();
+
+        assertStopped(result, 200);
+        assertSuccessFul(handle.startAndAwaitResult(Integer.MAX_VALUE, TimeUnit.SECONDS),
206, m_200digest);
     }
 
     @Test
     public void testFailed404_noresume_result() throws Exception {
         DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
-        final DownloadResult result = downloadHandler.getHandle(m_404url).start().result();
+
+        DownloadResult result = downloadHandler.getHandle(m_404url).startAndAwaitResult(10,
TimeUnit.SECONDS);
         assertFailed(result, 404);
     }
 
     @Test
     public void testFailed503_noresume_result() throws Exception {
         DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
-        DownloadResult result = downloadHandler.getHandle(m_503url).start().result();
+
+        DownloadHandle handle = downloadHandler.getHandle(m_503url);
+
+        DownloadResult result = handle.startAndAwaitResult(10, TimeUnit.SECONDS);
+        assertFailed(result, 503);
+
+        result = handle.startAndAwaitResult(10, TimeUnit.SECONDS);
         assertFailed(result, 503);
-        assertNotNull(result.getHeaders().get("Retry-After"), "Expected a Retry-After header
from error servlet");
-        assertNotNull(result.getHeaders().get("Retry-After").get(0), "Expected a Retry-After
header from error servlet");
-        assertEquals(result.getHeaders().get("Retry-After").get(0), "500", "Expected a Retry-After
header from error servlet");
     }
 
     private static void assertSuccessFul(final DownloadResult result, int statusCode, String
digest) throws Exception {
         assertEquals(result.getState(), DownloadState.SUCCESSFUL, "Expected state SUCCESSFUL
after succesful completion");
         assertEquals(result.getCode(), statusCode, "Expected statusCode " + statusCode +
" after successful completion");
         assertNotNull(result.getInputStream(), "Expected non null file after successful completion");
-        assertNotNull(result.getHeaders(), "Expected non null headers after successful completion");
         assertNull(result.getCause(), "Excpected null cause after successful completion");
         assertEquals(getDigest(result.getInputStream()), digest, "Expected same digest after
successful completion");
     }
@@ -234,7 +213,6 @@ public class DownloadHandlerTest extends
     private static void assertStopped(final DownloadResult result, int statusCode) throws
Exception {
         assertEquals(result.getState(), DownloadState.STOPPED, "DownloadState must be STOPPED
after stopped completion");
         assertEquals(result.getCode(), statusCode, "Expected statusCode " + statusCode +
" after stopped completion");
-        assertNotNull(result.getHeaders(), "Expected headers not to be null after stopped
completion");
         assertNull(result.getInputStream(), "File must not be null after failed download");
         assertNull(result.getCause(), "Excpected cause to null null after stopped completion");
     }



Mime
View raw message