changeset 2642:f540b9fe8771

Update VmGcStatDAO to communicate with web gateway. Reviewed by: ebaron Review Thread: http://icedtea.classpath.org/pipermail/thermostat/2017-May/023021.html
author Joshua Matsuoka <jmatsuok@redhat.com>
date Wed, 10 May 2017 13:48:56 -0400
parents 15401090ca15
children 26cec0f14ad6
files distribution/assembly/plugin-assembly.xml plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/VmGcStatDAO.java plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/Activator.java plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImpl.java plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImplStatementDescriptorRegistration.java plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/ActivatorTest.java plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImplStatementDescriptorRegistrationTest.java plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOTest.java
diffstat 8 files changed, 137 insertions(+), 611 deletions(-) [+]
line wrap: on
line diff
--- a/distribution/assembly/plugin-assembly.xml	Wed May 10 13:39:39 2017 -0400
+++ b/distribution/assembly/plugin-assembly.xml	Wed May 10 13:48:56 2017 -0400
@@ -58,7 +58,7 @@
 <!--        <include>com.redhat.thermostat:thermostat-vm-classstat-distribution</include>-->
 <!--        <include>com.redhat.thermostat:thermostat-vm-compiler-distribution</include>-->
 <!--        <include>com.redhat.thermostat:thermostat-vm-cpu-distribution</include>-->
-<!--        <include>com.redhat.thermostat:thermostat-vm-gc-distribution</include>-->
+        <include>com.redhat.thermostat:thermostat-vm-gc-distribution</include>
 <!--        <include>com.redhat.thermostat:thermostat-vm-heap-analysis-distribution</include>-->
 <!--        <include>com.redhat.thermostat:thermostat-vm-io-distribution</include>-->
 <!--        <include>com.redhat.thermostat:thermostat-vm-jmx-distribution</include>-->
--- a/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/VmGcStatDAO.java	Wed May 10 13:39:39 2017 -0400
+++ b/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/VmGcStatDAO.java	Wed May 10 13:48:56 2017 -0400
@@ -60,36 +60,6 @@
             Arrays.<Key<?>>asList(Key.AGENT_ID, Key.VM_ID, Key.TIMESTAMP, collectorKey, runCountKey, wallTimeKey),
             Arrays.<Key<?>>asList(Key.TIMESTAMP));
 
-    @Deprecated
-    public List<VmGcStat> getLatestVmGcStats(VmRef ref, long since);
-
-    public List<VmGcStat> getLatestVmGcStats(AgentId agentId, VmId vmId, long since);
-    
-    /**
-     * Find the set of distinct collector names for this JVM. For each JVM there
-     * are potentially multiple collectors recorded in storage.
-     * 
-     * @param ref
-     *            The idendifier of the JVM for which to get the collector names
-     *            for.
-     * @return A set of distinct collector names.
-     *
-     * @deprecated use {@link #getDistinctCollectorNames(VmId)}
-     */
-    @Deprecated
-    public Set<String> getDistinctCollectorNames(VmRef ref);
-
-    /**
-     * Find the set of distinct collector names for this JVM. For each JVM there
-     * are potentially multiple collectors recorded in storage.
-     *
-     * @param vmId
-     *            The idendifier of the JVM for which to get the collector names
-     *            for.
-     * @return A set of distinct collector names.
-     */
-    public Set<String> getDistinctCollectorNames(VmId vmId);
-    
     public void putVmGcStat(VmGcStat stat);
 }
 
--- a/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/Activator.java	Wed May 10 13:39:39 2017 -0400
+++ b/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/Activator.java	Wed May 10 13:48:56 2017 -0400
@@ -38,42 +38,21 @@
 
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
 
-import com.redhat.thermostat.storage.core.Storage;
 import com.redhat.thermostat.vm.gc.common.VmGcStatDAO;
 
 public class Activator implements BundleActivator {
-    
-    private ServiceTracker tracker;
-    private ServiceRegistration reg;
 
     @Override
     public void start(BundleContext context) throws Exception {
-        tracker = new ServiceTracker(context, Storage.class.getName(), null) {
-            @Override
-            public Object addingService(ServiceReference reference) {
-                Storage storage = (Storage) context.getService(reference);
-                VmGcStatDAO vmGcStatDao = new VmGcStatDAOImpl(storage);
-                reg = context.registerService(VmGcStatDAO.class.getName(), vmGcStatDao, null);
-                return super.addingService(reference);
-            }
-            
-            @Override
-            public void removedService(ServiceReference reference,
-                    Object service) {
-                reg.unregister();
-                super.removedService(reference, service);
-            }
-        };
-        tracker.open();
+        VmGcStatDAO vmGcStatDao = new VmGcStatDAOImpl();
+        context.registerService(VmGcStatDAO.class.getName(), vmGcStatDao, null);
     }
 
     @Override
     public void stop(BundleContext context) throws Exception {
-        tracker.close();
+        // Nothing to do here. The OSGi framework will automatically
+        // unregister the service when the bundle is stopped.
     }
 
 }
--- a/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImpl.java	Wed May 10 13:39:39 2017 -0400
+++ b/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImpl.java	Wed May 10 13:48:56 2017 -0400
@@ -36,118 +36,108 @@
 
 package com.redhat.thermostat.vm.gc.common.internal;
 
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+import java.util.logging.Level;
 import java.util.logging.Logger;
 
 import com.redhat.thermostat.common.utils.LoggingUtils;
-import com.redhat.thermostat.storage.core.AgentId;
-import com.redhat.thermostat.storage.core.Category;
-import com.redhat.thermostat.storage.core.CategoryAdapter;
-import com.redhat.thermostat.storage.core.Key;
-import com.redhat.thermostat.storage.core.PreparedStatement;
-import com.redhat.thermostat.storage.core.Storage;
-import com.redhat.thermostat.storage.core.VmId;
-import com.redhat.thermostat.storage.core.VmLatestPojoListGetter;
-import com.redhat.thermostat.storage.core.VmRef;
 import com.redhat.thermostat.storage.dao.AbstractDao;
-import com.redhat.thermostat.storage.dao.AbstractDaoQuery;
-import com.redhat.thermostat.storage.dao.AbstractDaoStatement;
-import com.redhat.thermostat.storage.model.DistinctResult;
 import com.redhat.thermostat.vm.gc.common.VmGcStatDAO;
 import com.redhat.thermostat.vm.gc.common.model.VmGcStat;
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.api.ContentResponse;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.client.util.StringContentProvider;
+import org.eclipse.jetty.http.HttpMethod;
+import org.eclipse.jetty.http.HttpStatus;
 
 public class VmGcStatDAOImpl extends AbstractDao implements VmGcStatDAO {
     
     private static Logger logger = LoggingUtils.getLogger(VmGcStatDAOImpl.class);
-    // ADD vm-gc-stats SET 'agentId' = ?s , \
-    //                     'vmId' = ?s , \
-    //                     'timeStamp' = ?l , \
-    //                     'collectorName' = ?s , \
-    //                     'runCount' = ?l , \
-    //                     'wallTime' = ?l
-    static final String DESC_ADD_VM_GC_STAT = "ADD " + vmGcStatCategory.getName() +
-            " SET '" + Key.AGENT_ID.getName() + "' = ?s , " +
-                 "'" + Key.VM_ID.getName() + "' = ?s , " +
-                 "'" + Key.TIMESTAMP.getName() + "' = ?l , " +
-                 "'" + collectorKey.getName() + "' = ?s , " +
-                 "'" + runCountKey.getName() + "' = ?l , " +
-                 "'" + wallTimeKey.getName() + "' = ?l";
-    // The assumption is that VM id's are unique. Which it is. It's a UUID.
-    static final String DESC_QUERY_DISTINCT_COLLECTORS = "QUERY-DISTINCT(" +
-            collectorKey.getName() + ") " + vmGcStatCategory.getName() +
-            " WHERE '" + Key.VM_ID.getName() + "' = ?s";
-    
+    private final JsonHelper jsonHelper;
+    private final HttpHelper httpHelper;
+    private final HttpClient httpClient;
 
-    private final Storage storage;
-    private final VmLatestPojoListGetter<VmGcStat> getter;
-    private final Category<DistinctResult> aggregateCategory;
+    static final String GATEWAY_URL = "http://localhost:30000"; // TODO configurable
+    static final String GATEWAY_PATH = "/jvm-gc/0.0.2/";
+    static final String CONTENT_TYPE = "application/json";
 
-    VmGcStatDAOImpl(Storage storage) {
-        this.storage = storage;
-        storage.registerCategory(vmGcStatCategory);
-        // getDistinctCollectorNames uses an adapted category. Be sure to
-        // register it after the source category has been registered. This is
-        // necessary in order for web storage to work with the adapted
-        // category.
-        CategoryAdapter<VmGcStat, DistinctResult> adapter = new CategoryAdapter<>(vmGcStatCategory);
-        this.aggregateCategory = adapter.getAdapted(DistinctResult.class);
-        storage.registerCategory(aggregateCategory);
-        getter = new VmLatestPojoListGetter<>(storage, vmGcStatCategory);
+    VmGcStatDAOImpl() throws Exception {
+        this(new HttpClient(), new JsonHelper(new VmGcStatTypeAdapter()), new HttpHelper());
     }
 
-    @Override
-    public List<VmGcStat> getLatestVmGcStats(VmRef ref, long since) {
-        return getter.getLatest(ref, since);
-    }
+    VmGcStatDAOImpl(HttpClient client, JsonHelper jh, HttpHelper hh) throws Exception {
+        this.httpClient = client;
+        this.jsonHelper = jh;
+        this.httpHelper = hh;
 
-    @Override
-    public List<VmGcStat> getLatestVmGcStats(AgentId agentId, VmId vmId, long since) {
-        return getter.getLatest(agentId, vmId, since);
+        this.httpHelper.startClient(this.httpClient);
     }
 
     @Override
     public void putVmGcStat(final VmGcStat stat) {
-        executeStatement(new AbstractDaoStatement<VmGcStat>(storage, vmGcStatCategory, DESC_ADD_VM_GC_STAT) {
-            @Override
-            public PreparedStatement<VmGcStat> customize(PreparedStatement<VmGcStat> preparedStatement) {
-                preparedStatement.setString(0, stat.getAgentId());
-                preparedStatement.setString(1, stat.getVmId());
-                preparedStatement.setLong(2, stat.getTimeStamp());
-                preparedStatement.setString(3, stat.getCollectorName());
-                preparedStatement.setLong(4, stat.getRunCount());
-                preparedStatement.setLong(5, stat.getWallTime());
-                return preparedStatement;
-            }
-        });
-    }
+        try {
+            String json = jsonHelper.toJson(stat);
+            StringContentProvider provider = httpHelper.createContentProvider(json);
 
-    @Override
-    public Set<String> getDistinctCollectorNames(VmRef ref) {
-        return getDistinctCollectorNames(new VmId(ref.getVmId()));
-    }
-
-    @Override
-    public Set<String> getDistinctCollectorNames(final VmId vmId) {
-        DistinctResult distinctResult = executeQuery(new AbstractDaoQuery<DistinctResult>(storage, aggregateCategory, DESC_QUERY_DISTINCT_COLLECTORS) {
-            @Override
-            public PreparedStatement<DistinctResult> customize(PreparedStatement<DistinctResult> preparedStatement) {
-                preparedStatement.setString(0, vmId.get());
-                return preparedStatement;
-            }
-        }).head();
-        Set<String> collNames = new HashSet<>();
-        if (distinctResult != null) {
-            Collections.addAll(collNames, distinctResult.getValues());
+            String url = buildUrl();
+            Request httpRequest = httpClient.newRequest(url);
+            httpRequest.method(HttpMethod.POST);
+            httpRequest.content(provider, CONTENT_TYPE);
+            sendRequest(httpRequest);
+        } catch (Exception e) {
+            logger.log(Level.WARNING, "Failed to send VmGcStat information to web gateway", e);
         }
-        return collNames;
     }
 
     @Override
     public Logger getLogger() {
         return logger;
     }
+
+    private String buildUrl() {
+        StringBuilder builder = new StringBuilder();
+        builder.append(GATEWAY_URL);
+        builder.append(GATEWAY_PATH);
+        return builder.toString();
+    }
+
+    private void sendRequest(Request httpRequest)
+            throws InterruptedException, TimeoutException, ExecutionException, IOException {
+        ContentResponse resp = httpRequest.send();
+        int status = resp.getStatus();
+        if (status != HttpStatus.OK_200) {
+            throw new IOException("Gateway returned HTTP status " + String.valueOf(status) + " - " + resp.getReason());
+        }
+    }
+
+    // For Testing purposes
+    static class JsonHelper {
+
+        private final VmGcStatTypeAdapter adapter;
+
+        public JsonHelper(VmGcStatTypeAdapter adapter) {
+            this.adapter = adapter;
+        }
+
+        public String toJson(VmGcStat stat) throws IOException {
+            return adapter.toJson(stat);
+        }
+
+    }
+
+    // For Testing purposes
+    static class HttpHelper {
+
+        void startClient(HttpClient httpClient) throws Exception {
+            httpClient.start();
+        }
+
+        StringContentProvider createContentProvider(String content) {
+            return new StringContentProvider(content);
+        }
+    }
 }
 
--- a/plugins/vm-gc/common/src/main/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImplStatementDescriptorRegistration.java	Wed May 10 13:39:39 2017 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,68 +0,0 @@
-/*
- * Copyright 2012-2017 Red Hat, Inc.
- *
- * This file is part of Thermostat.
- *
- * Thermostat is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 2, or (at your
- * option) any later version.
- *
- * Thermostat is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Thermostat; see the file COPYING.  If not see
- * <http://www.gnu.org/licenses/>.
- *
- * Linking this code with other modules is making a combined work
- * based on this code.  Thus, the terms and conditions of the GNU
- * General Public License cover the whole combination.
- *
- * As a special exception, the copyright holders of this code give
- * you permission to link this code with independent modules to
- * produce an executable, regardless of the license terms of these
- * independent modules, and to copy and distribute the resulting
- * executable under terms of your choice, provided that you also
- * meet, for each linked independent module, the terms and conditions
- * of the license of that module.  An independent module is a module
- * which is not derived from or based on this code.  If you modify
- * this code, you may extend this exception to your version of the
- * library, but you are not obligated to do so.  If you do not wish
- * to do so, delete this exception statement from your version.
- */
-
-package com.redhat.thermostat.vm.gc.common.internal;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import com.redhat.thermostat.storage.core.VmLatestPojoListGetter;
-import com.redhat.thermostat.storage.core.auth.StatementDescriptorRegistration;
-import com.redhat.thermostat.vm.gc.common.VmGcStatDAO;
-
-/**
- * Registers the prepared query issued by this maven module via
- * {@link VmLatestPojoListGetter}.
- * 
- */
-public class VmGcStatDAOImplStatementDescriptorRegistration implements
-        StatementDescriptorRegistration {
-
-    static final String descriptor = String.format(
-            VmLatestPojoListGetter.VM_LATEST_QUERY_FORMAT,
-            VmGcStatDAO.vmGcStatCategory.getName());
-
-    @Override
-    public Set<String> getStatementDescriptors() {
-        Set<String> descs = new HashSet<>();
-        descs.add(descriptor);
-        descs.add(VmGcStatDAOImpl.DESC_ADD_VM_GC_STAT);
-        descs.add(VmGcStatDAOImpl.DESC_QUERY_DISTINCT_COLLECTORS);
-        return descs;
-    }
-
-}
-
--- a/plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/ActivatorTest.java	Wed May 10 13:39:39 2017 -0400
+++ b/plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/ActivatorTest.java	Wed May 10 13:48:56 2017 -0400
@@ -38,36 +38,17 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
 
 import org.junit.Test;
 
-import com.redhat.thermostat.storage.core.Storage;
 import com.redhat.thermostat.testutils.StubBundleContext;
 import com.redhat.thermostat.vm.gc.common.VmGcStatDAO;
 
 public class ActivatorTest {
-    
-    @Test
-    public void verifyActivatorDoesNotRegisterServiceOnMissingDeps() throws Exception {
-        StubBundleContext context = new StubBundleContext();
-
-        Activator activator = new Activator();
-
-        activator.start(context);
-
-        assertEquals(0, context.getAllServices().size());
-        assertEquals(1, context.getServiceListeners().size());
-
-        activator.stop(context);
-    }
 
     @Test
     public void verifyActivatorRegistersServices() throws Exception {
         StubBundleContext context = new StubBundleContext();
-        Storage storage = mock(Storage.class);
-
-        context.registerService(Storage.class, storage, null);
 
         Activator activator = new Activator();
 
@@ -81,5 +62,4 @@
         assertEquals(1, context.getAllServices().size());
     }
 
-}
-
+}
\ No newline at end of file
--- a/plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOImplStatementDescriptorRegistrationTest.java	Wed May 10 13:39:39 2017 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,100 +0,0 @@
-/*
- * Copyright 2012-2017 Red Hat, Inc.
- *
- * This file is part of Thermostat.
- *
- * Thermostat is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 2, or (at your
- * option) any later version.
- *
- * Thermostat is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Thermostat; see the file COPYING.  If not see
- * <http://www.gnu.org/licenses/>.
- *
- * Linking this code with other modules is making a combined work
- * based on this code.  Thus, the terms and conditions of the GNU
- * General Public License cover the whole combination.
- *
- * As a special exception, the copyright holders of this code give
- * you permission to link this code with independent modules to
- * produce an executable, regardless of the license terms of these
- * independent modules, and to copy and distribute the resulting
- * executable under terms of your choice, provided that you also
- * meet, for each linked independent module, the terms and conditions
- * of the license of that module.  An independent module is a module
- * which is not derived from or based on this code.  If you modify
- * this code, you may extend this exception to your version of the
- * library, but you are not obligated to do so.  If you do not wish
- * to do so, delete this exception statement from your version.
- */
-
-package com.redhat.thermostat.vm.gc.common.internal;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-import java.util.Set;
-
-import org.junit.Test;
-
-import com.redhat.thermostat.storage.core.auth.StatementDescriptorRegistration;
-import com.redhat.thermostat.testutils.ServiceLoaderTest;
-
-/*
- * Copyright 2012-2014 Red Hat, Inc.
- *
- * This file is part of Thermostat.
- *
- * Thermostat is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 2, or (at your
- * option) any later version.
- *
- * Thermostat is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Thermostat; see the file COPYING.  If not see
- * <http://www.gnu.org/licenses/>.
- *
- * Linking this code with other modules is making a combined work
- * based on this code.  Thus, the terms and conditions of the GNU
- * General Public License cover the whole combination.
- *
- * As a special exception, the copyright holders of this code give
- * you permission to link this code with independent modules to
- * produce an executable, regardless of the license terms of these
- * independent modules, and to copy and distribute the resulting
- * executable under terms of your choice, provided that you also
- * meet, for each linked independent module, the terms and conditions
- * of the license of that module.  An independent module is a module
- * which is not derived from or based on this code.  If you modify
- * this code, you may extend this exception to your version of the
- * library, but you are not obligated to do so.  If you do not wish
- * to do so, delete this exception statement from your version.
- */
-
-public class VmGcStatDAOImplStatementDescriptorRegistrationTest extends ServiceLoaderTest<StatementDescriptorRegistration> {
-
-    public VmGcStatDAOImplStatementDescriptorRegistrationTest() {
-        super(StatementDescriptorRegistration.class, STORAGE_SERVICES, VmGcStatDAOImplStatementDescriptorRegistration.class);
-    }
-
-    @Test
-    public void registersAllDescriptors() {
-        VmGcStatDAOImplStatementDescriptorRegistration reg = new VmGcStatDAOImplStatementDescriptorRegistration();
-        Set<String> descriptors = reg.getStatementDescriptors();
-        assertEquals(3, descriptors.size());
-        assertFalse("null descriptor not allowed", descriptors.contains(null));
-    }
-
-}
-
--- a/plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOTest.java	Wed May 10 13:39:39 2017 -0400
+++ b/plugins/vm-gc/common/src/test/java/com/redhat/thermostat/vm/gc/common/internal/VmGcStatDAOTest.java	Wed May 10 13:48:56 2017 -0400
@@ -37,70 +37,80 @@
 package com.redhat.thermostat.vm.gc.common.internal;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.when;
+import static com.redhat.thermostat.vm.gc.common.internal.VmGcStatDAOImpl.HttpHelper;
+import static com.redhat.thermostat.vm.gc.common.internal.VmGcStatDAOImpl.JsonHelper;
 
 import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Set;
 
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.api.ContentResponse;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.client.util.StringContentProvider;
+import org.eclipse.jetty.http.HttpMethod;
+import org.eclipse.jetty.http.HttpStatus;
+import org.junit.Before;
 import org.junit.Test;
 
-import com.redhat.thermostat.storage.core.AgentId;
-import com.redhat.thermostat.storage.core.Category;
-import com.redhat.thermostat.storage.core.CategoryAdapter;
-import com.redhat.thermostat.storage.core.Cursor;
-import com.redhat.thermostat.storage.core.DescriptorParsingException;
-import com.redhat.thermostat.storage.core.HostRef;
-import com.redhat.thermostat.storage.core.Key;
-import com.redhat.thermostat.storage.core.PreparedStatement;
-import com.redhat.thermostat.storage.core.StatementDescriptor;
-import com.redhat.thermostat.storage.core.StatementExecutionException;
-import com.redhat.thermostat.storage.core.Storage;
-import com.redhat.thermostat.storage.core.VmId;
-import com.redhat.thermostat.storage.core.VmRef;
-import com.redhat.thermostat.storage.model.DistinctResult;
 import com.redhat.thermostat.vm.gc.common.VmGcStatDAO;
 import com.redhat.thermostat.vm.gc.common.model.VmGcStat;
+import com.redhat.thermostat.storage.core.Key;
 
 public class VmGcStatDAOTest {
 
-    static class Triple<S, T, U> {
-        final S first;
-        final T second;
-        final U third;
+    private VmGcStat stat;
+    private HttpClient httpClient;
+    private HttpHelper httpHelper;
+    private JsonHelper jsonHelper;
+    private StringContentProvider contentProvider;
+    private Request request;
+    private ContentResponse response;
+    private static final String AGENT_ID = "some-agent";
+    private static final String JSON = "{\"this\":\"is\",\"also\":\"JSON\"}";
 
-        public Triple(S first, T second, U third) {
-            this.first = first;
-            this.second = second;
-            this.third = third;
-        }
+    @Before
+    public void setup() throws Exception {
+        stat = new VmGcStat();
+        stat.setAgentId(AGENT_ID);
+        stat.setTimeStamp(1234l);
+        stat.setWallTime(4000l);
+        stat.setRunCount(1000l);
+        stat.setVmId("Vm-1");
+        stat.setCollectorName("Collector");
+
+        httpClient = mock(HttpClient.class);
+        request = mock(Request.class);
+        when(httpClient.newRequest(anyString())).thenReturn(request);
+        response = mock(ContentResponse.class);
+        when(response.getStatus()).thenReturn(HttpStatus.OK_200);
+        when(request.send()).thenReturn(response);
+
+        jsonHelper = mock(JsonHelper.class);
+        when(jsonHelper.toJson(any(VmGcStat.class))).thenReturn(JSON);
+        httpHelper = mock(HttpHelper.class);
+        contentProvider = mock(StringContentProvider.class);
+        when(httpHelper.createContentProvider(anyString())).thenReturn(contentProvider);
     }
 
-    private static final String AGENT_ID = "some-agent";
-    private static final String VM_ID = "VM321";
-    private static final Long TIMESTAMP = 456L;
-    private static final String COLLECTOR = "collector1";
-    private static final Long RUN_COUNT = 10L;
-    private static final Long WALL_TIME = 9L;
-    
     @Test
-    public void verifyDescriptorsAreSane() {
-        String addVmGcStat = "ADD vm-gc-stats SET 'agentId' = ?s , " +
-                                    "'vmId' = ?s , " +
-                                    "'timeStamp' = ?l , " +
-                                    "'collectorName' = ?s , " +
-                                    "'runCount' = ?l , " +
-                                    "'wallTime' = ?l";
-        assertEquals(addVmGcStat, VmGcStatDAOImpl.DESC_ADD_VM_GC_STAT);
+    public void verifyAddVmGcStat() throws Exception {
+        VmGcStatDAO dao = new VmGcStatDAOImpl(httpClient, jsonHelper, httpHelper);
+
+        dao.putVmGcStat(stat);
+
+        final String url = VmGcStatDAOImpl.GATEWAY_URL + VmGcStatDAOImpl.GATEWAY_PATH;
+        verify(httpClient).newRequest(url);
+        verify(request).method(HttpMethod.POST);
+        verify(jsonHelper).toJson(stat);
+        verify(httpHelper).createContentProvider(JSON);
+        verify(request).content(contentProvider, VmGcStatDAOImpl.CONTENT_TYPE);
+        verify(request).send();
+        verify(response).getStatus();
     }
 
     @Test
@@ -116,241 +126,6 @@
         assertEquals(6, keys.size());
     }
 
-    @Test
-    public void testGetLatestVmGcStatsBasic() throws DescriptorParsingException, StatementExecutionException {
-
-        VmGcStat vmGcStat = new VmGcStat("foo-agent", VM_ID, TIMESTAMP, COLLECTOR, RUN_COUNT, WALL_TIME);
-
-        @SuppressWarnings("unchecked")
-        Cursor<VmGcStat> cursor = (Cursor<VmGcStat>) mock(Cursor.class);
-        when(cursor.hasNext()).thenReturn(true).thenReturn(false);
-        when(cursor.next()).thenReturn(vmGcStat);
-
-        Storage storage = mock(Storage.class);
-        @SuppressWarnings("unchecked")
-        PreparedStatement<VmGcStat> stmt = (PreparedStatement<VmGcStat>) mock(PreparedStatement.class);
-        when(storage.prepareStatement(anyDescriptor())).thenReturn(stmt);
-        when(stmt.executeQuery()).thenReturn(cursor);
-
-        HostRef hostRef = mock(HostRef.class);
-        when(hostRef.getAgentId()).thenReturn("system");
-
-        VmRef vmRef = mock(VmRef.class);
-        when(vmRef.getHostRef()).thenReturn(hostRef);
-        when(vmRef.getVmId()).thenReturn("VM321");
-
-        VmGcStatDAO dao = new VmGcStatDAOImpl(storage);
-        List<VmGcStat> vmGcStats = dao.getLatestVmGcStats(vmRef, Long.MIN_VALUE);
-
-        verify(storage).prepareStatement(anyDescriptor());
-        verify(stmt).setString(0, "system");
-        verify(stmt).setString(1, "VM321");
-        verify(stmt).setLong(2, Long.MIN_VALUE);
-        verify(stmt).executeQuery();
-        verifyNoMoreInteractions(stmt);
-
-        assertEquals(1, vmGcStats.size());
-        VmGcStat stat = vmGcStats.get(0);
-        assertEquals(TIMESTAMP, (Long) stat.getTimeStamp());
-        assertEquals(VM_ID, stat.getVmId());
-        assertEquals(COLLECTOR, stat.getCollectorName());
-        assertEquals(RUN_COUNT, (Long) stat.getRunCount());
-        assertEquals(WALL_TIME, (Long) stat.getWallTime());
-    }
-
-    @Test
-    public void testGetLatestVmGcStatsFromAgentIdAndVmId() throws DescriptorParsingException, StatementExecutionException {
-        AgentId agentId = new AgentId(AGENT_ID);
-        VmId vmId = new VmId(VM_ID);
-        VmGcStat vmGcStat = new VmGcStat(AGENT_ID, VM_ID, TIMESTAMP, COLLECTOR, RUN_COUNT, WALL_TIME);
-
-        @SuppressWarnings("unchecked")
-        Cursor<VmGcStat> cursor = (Cursor<VmGcStat>) mock(Cursor.class);
-        when(cursor.hasNext()).thenReturn(true).thenReturn(false);
-        when(cursor.next()).thenReturn(vmGcStat);
-
-        Storage storage = mock(Storage.class);
-        @SuppressWarnings("unchecked")
-        PreparedStatement<VmGcStat> stmt = (PreparedStatement<VmGcStat>) mock(PreparedStatement.class);
-        when(storage.prepareStatement(anyDescriptor())).thenReturn(stmt);
-        when(stmt.executeQuery()).thenReturn(cursor);
-
-        VmGcStatDAO dao = new VmGcStatDAOImpl(storage);
-        List<VmGcStat> vmGcStats = dao.getLatestVmGcStats(agentId, vmId, Long.MIN_VALUE);
-
-        verify(storage).prepareStatement(anyDescriptor());
-        verify(stmt).setString(0, AGENT_ID);
-        verify(stmt).setString(1, VM_ID);
-        verify(stmt).setLong(2, Long.MIN_VALUE);
-        verify(stmt).executeQuery();
-        verifyNoMoreInteractions(stmt);
-
-        assertEquals(1, vmGcStats.size());
-        VmGcStat stat = vmGcStats.get(0);
-        assertEquals(TIMESTAMP, (Long) stat.getTimeStamp());
-        assertEquals(AGENT_ID, stat.getAgentId());
-        assertEquals(VM_ID, stat.getVmId());
-        assertEquals(COLLECTOR, stat.getCollectorName());
-        assertEquals(RUN_COUNT, (Long) stat.getRunCount());
-        assertEquals(WALL_TIME, (Long) stat.getWallTime());
-    }
-
-    @SuppressWarnings("unchecked")
-    private StatementDescriptor<VmGcStat> anyDescriptor() {
-        return (StatementDescriptor<VmGcStat>) any(StatementDescriptor.class);
-    }
-
-    @Test
-    public void testPutVmGcStat() throws DescriptorParsingException,
-            StatementExecutionException {
-        Storage storage = mock(Storage.class);
-        @SuppressWarnings("unchecked")
-        PreparedStatement<VmGcStat> add = mock(PreparedStatement.class);
-        StatementDescriptor<VmGcStat> desc = new StatementDescriptor<>(VmGcStatDAO.vmGcStatCategory, VmGcStatDAOImpl.DESC_ADD_VM_GC_STAT);
-        
-        when(storage.prepareStatement(eq(desc))).thenReturn(add);
-        
-        VmGcStat stat = new VmGcStat("foo-agent", VM_ID, TIMESTAMP, COLLECTOR, RUN_COUNT, WALL_TIME);
-        VmGcStatDAO dao = new VmGcStatDAOImpl(storage);
-        dao.putVmGcStat(stat);
-        
-        verify(storage).prepareStatement(eq(desc));
-
-        verify(add).setString(0, stat.getAgentId());
-        verify(add).setString(1, stat.getVmId());
-        verify(add).setLong(2, stat.getTimeStamp());
-        verify(add).setString(3, stat.getCollectorName());
-        verify(add).setLong(4, stat.getRunCount());
-        verify(add).setLong(5, stat.getWallTime());
-        verify(add).execute();
-        verifyNoMoreInteractions(add);
-    }
-
-    @Test
-    public void testVmRefDistinctCollectorsSuccess() throws DescriptorParsingException,
-            StatementExecutionException {
-
-        Triple<Cursor<DistinctResult>, DistinctResult, Set<String>> setup =
-                setupTestDistinctCollectorsSuccess();
-        Cursor<DistinctResult> c = setup.first;
-        DistinctResult result = setup.second;
-        Set<String> mockResults = setup.third;
-
-        Set<String> actual = doVmRefDistinctCollectorsTest(c);
-        assertNotNull(result);
-        assertEquals(2, actual.size());
-        assertEquals(mockResults, actual);
-    }
-
-    @Test
-    public void testDistinctCollectorsSuccess() throws DescriptorParsingException,
-            StatementExecutionException {
-
-        Triple<Cursor<DistinctResult>, DistinctResult, Set<String>> setup =
-                setupTestDistinctCollectorsSuccess();
-        Cursor<DistinctResult> c = setup.first;
-        DistinctResult result = setup.second;
-        Set<String> mockResults = setup.third;
-        
-        Set<String> actual = doDistinctCollectorsTest(c);
-        assertNotNull(result);
-        assertEquals(2, actual.size());
-        assertEquals(mockResults, actual);
-    }
-
-    private Triple<Cursor<DistinctResult>, DistinctResult, Set<String>> setupTestDistinctCollectorsSuccess()
-            throws DescriptorParsingException {
-
-        Set<String> mockResults = new HashSet<>();
-        mockResults.add("MSC");
-        mockResults.add("PCopy");
-        String[] vals = mockResults.toArray(new String[mockResults.size()]);
-        DistinctResult result = new DistinctResult();
-        result.setValues(vals);
-        @SuppressWarnings("unchecked")
-        Cursor<DistinctResult> c = mock(Cursor.class);
-        when(c.hasNext()).thenReturn(true).thenReturn(false);
-        when(c.next()).thenReturn(result).thenThrow(new NoSuchElementException());
-
-        return new Triple<>(c, result, mockResults);
-    }
-    
-    @Test
-    public void testVmRefDistinctCollectorsQueryFailure() throws DescriptorParsingException,
-            StatementExecutionException {
-        @SuppressWarnings("unchecked")
-        Cursor<DistinctResult> c = mock(Cursor.class);
-        when(c.hasNext()).thenReturn(false);
-        
-        Set<String> result = doVmRefDistinctCollectorsTest(c);
-        assertEquals("expected empty set", 0, result.size());
-    }
-
-    @Test
-    public void testDistinctCollectorsQueryFailure() throws DescriptorParsingException,
-            StatementExecutionException {
-        @SuppressWarnings("unchecked")
-        Cursor<DistinctResult> c = mock(Cursor.class);
-        when(c.hasNext()).thenReturn(false);
-
-        Set<String> result = doDistinctCollectorsTest(c);
-        assertEquals("expected empty set", 0, result.size());
-    }
-
-    private Set<String> doVmRefDistinctCollectorsTest(Cursor<DistinctResult> c)
-            throws DescriptorParsingException, StatementExecutionException {
-
-        Triple<Storage, PreparedStatement<DistinctResult>, StatementDescriptor<DistinctResult>>
-                setup = setupDoDistinctCollectorsTest(c);
-        Storage storage = setup.first;
-        PreparedStatement<DistinctResult> query = setup.second;
-        StatementDescriptor<DistinctResult> desc = setup.third;
-
-        VmGcStatDAO dao = new VmGcStatDAOImpl(storage);
-        Set<String> result = dao.getDistinctCollectorNames(new VmRef(null, VM_ID, -1, "foo-vmref"));
-        
-        verify(storage).prepareStatement(eq(desc));
-        verify(query).setString(0, VM_ID);
-        verify(query).executeQuery();
-        verifyNoMoreInteractions(query);
-        return result;
-    }
-
-    private Set<String> doDistinctCollectorsTest(Cursor<DistinctResult> c)
-            throws DescriptorParsingException, StatementExecutionException {
-
-        Triple<Storage, PreparedStatement<DistinctResult>, StatementDescriptor<DistinctResult>>
-                setup = setupDoDistinctCollectorsTest(c);
-        Storage storage = setup.first;
-        PreparedStatement<DistinctResult> query = setup.second;
-        StatementDescriptor<DistinctResult> desc = setup.third;
-
-        VmGcStatDAO dao = new VmGcStatDAOImpl(storage);
-        Set<String> result = dao.getDistinctCollectorNames(new VmId(VM_ID));
-
-        verify(storage).prepareStatement(eq(desc));
-        verify(query).setString(0, VM_ID);
-        verify(query).executeQuery();
-        verifyNoMoreInteractions(query);
-        return result;
-    }
-
-    private Triple<Storage, PreparedStatement<DistinctResult>, StatementDescriptor<DistinctResult>> setupDoDistinctCollectorsTest
-            (Cursor<DistinctResult> c)
-            throws DescriptorParsingException, StatementExecutionException {
-
-        Storage storage = mock(Storage.class);
-        CategoryAdapter<VmGcStat, DistinctResult> catAdapter = new CategoryAdapter<>(VmGcStatDAO.vmGcStatCategory);
-        Category<DistinctResult> adaptedCategory = catAdapter.getAdapted(DistinctResult.class);
-        @SuppressWarnings("unchecked")
-        PreparedStatement<DistinctResult> query = mock(PreparedStatement.class);
-        StatementDescriptor<DistinctResult> desc = new StatementDescriptor<>(adaptedCategory, VmGcStatDAOImpl.DESC_QUERY_DISTINCT_COLLECTORS);
-
-        when(storage.prepareStatement(eq(desc))).thenReturn(query);
-        when(query.executeQuery()).thenReturn(c);
-
-        return new Triple<>(storage, query, desc);
-    }
 
 }