Merge branch 'stable-2.11' into stable-2.12

* stable-2.11:
  Change copyright to AOSP
  Build with API version 2.11.7

Change-Id: Iba3eea3738b1369f5659c9632b240b207015e214
diff --git a/.buckconfig b/.buckconfig
index 1e14e05..1e032e5 100644
--- a/.buckconfig
+++ b/.buckconfig
@@ -7,7 +7,7 @@
   src_roots = java, resources
 
 [project]
-  ignore = .git
+  ignore = .git, eclipse-out
 
 [cache]
   mode = dir
diff --git a/.gitignore b/.gitignore
index 0d230b2..50ce7fd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@
 .buckversion
 .watchmanconfig
 /bucklets
+/eclipse-out
diff --git a/BUCK b/BUCK
index 81ae99b..b7fea48 100644
--- a/BUCK
+++ b/BUCK
@@ -11,7 +11,6 @@
   ':events-log__plugin',
   '//lib/easymock:easymock',
   '//lib:gson',
-  '//lib:junit',
   '//lib:truth',
 ]
 
@@ -38,7 +37,6 @@
   name = 'events-log_tests',
   srcs = glob(['src/test/java/**/*.java']),
   labels = ['events-log'],
-  source_under_test = [':events-log__plugin'],
   deps = TEST_DEPS,
 )
 
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/lib/BUCK b/lib/BUCK
index 5e5b5bd..190d931 100644
--- a/lib/BUCK
+++ b/lib/BUCK
@@ -9,22 +9,31 @@
 
 maven_jar(
   name = 'guava',
-  id = 'com.google.guava:guava:18.0',
-  sha1 = 'cce0823396aa693798f8882e64213b1772032b09',
+  id = 'com.google.guava:guava:19.0-rc1',
+  sha1 = '0364538ac107b8943a1f4d68ac50f1b0421bb983',
   license = 'Apache2.0',
 )
 
 maven_jar(
   name = 'junit',
-  id = 'junit:junit:4.10',
-  sha1 = 'e4f1766ce7404a08f45d859fb9c226fc9e41a861',
+  id = 'junit:junit:4.11',
+  sha1 = '4e031bb61df09069aeb2bffb4019e7a5034a4ee0',
   license = 'DO_NOT_DISTRIBUTE',
+  exported_deps = [':hamcrest-core'],
+)
+
+maven_jar(
+  name = 'hamcrest-core',
+  id = 'org.hamcrest:hamcrest-core:1.3',
+  sha1 = '42a25dc3219429f0e5d060061f71acb49bf010a0',
+  license = 'DO_NOT_DISTRIBUTE',
+  visibility = ['//lib:junit'],
 )
 
 maven_jar(
   name = 'truth',
-  id = 'com.google.truth:truth:0.25',
-  sha1 = '503ba892e8482976b81eb2b2df292858fbac3782',
+  id = 'com.google.truth:truth:0.27',
+  sha1 = 'bd17774d2dc0fffa884d42c07d2537e86c67acd6',
   license = 'DO_NOT_DISTRIBUTE',
   exported_deps = [
     ':guava',
diff --git a/lib/easymock/BUCK b/lib/easymock/BUCK
index 2a774a9..11d95a4 100644
--- a/lib/easymock/BUCK
+++ b/lib/easymock/BUCK
@@ -2,8 +2,8 @@
 
 maven_jar(
   name = 'easymock',
-  id = 'org.easymock:easymock:3.2',
-  sha1 = '00c82f7fa3ef377d8954b1db25123944b5af2ba4',
+  id = 'org.easymock:easymock:3.3.1',
+  sha1 = 'a497d7f00c9af78b72b6d8f24762d9210309148a',
   license = 'DO_NOT_DISTRIBUTE',
   deps = [
     ':cglib-2_2',
@@ -21,8 +21,8 @@
 
 maven_jar(
   name = 'objenesis',
-  id = 'org.objenesis:objenesis:1.2',
-  sha1 = 'bfcb0539a071a4c5a30690388903ac48c0667f2a',
+  id = 'org.objenesis:objenesis:2.1',
+  sha1 = '87c0ea803b69252868d09308b4618f766f135a96',
   license = 'DO_NOT_DISTRIBUTE',
   visibility = ['//lib/powermock:powermock-reflect'],
   attach_source = False,
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK
index e0fa31f..0a0b2bc 100644
--- a/lib/gerrit/BUCK
+++ b/lib/gerrit/BUCK
@@ -1,12 +1,12 @@
 include_defs('//bucklets/maven_jar.bucklet')
 
-VER = '2.11.7'
+VER = '2.12'
 REPO = MAVEN_CENTRAL
 
 maven_jar(
   name = 'plugin-api',
   id = 'com.google.gerrit:gerrit-plugin-api:' + VER,
-  sha1 = 'e49e930c5c4ce74fc2c4c1cde1ddfb3ff77d0d63',
+  sha1 = '8ce1f6e65078bbcf03a1758f96b3ebca19b7fe3c',
   license = 'Apache2.0',
   attach_source = False,
   repository = REPO,
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventHandler.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventHandler.java
index 648ba89..3ba78bb 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventHandler.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventHandler.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -24,13 +24,13 @@
 /**
  * Listen to Events and store them into the EventStore
  */
-public class EventHandler implements EventListener {
-
+class EventHandler implements EventListener {
   private final EventStore store;
   private final ScheduledThreadPoolExecutor pool;
 
   @Inject
-  EventHandler(EventStore store, @EventPool ScheduledThreadPoolExecutor pool) {
+  EventHandler(EventStore store,
+      @EventPool ScheduledThreadPoolExecutor pool) {
     this.store = store;
     this.pool = pool;
   }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventModule.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventModule.java
index dfaae80..7619a82 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventModule.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventModule.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventPool.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventPool.java
index 6bb4e80..c51ac02 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventPool.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventPool.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -23,5 +23,4 @@
 @Retention(RUNTIME)
 @BindingAnnotation
 public @interface EventPool {
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventQueue.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventQueue.java
index 057f44a..07d5b41 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventQueue.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventQueue.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -20,6 +20,7 @@
 
 import java.util.concurrent.ScheduledThreadPoolExecutor;
 
+/** A queue for events to store. */
 public class EventQueue implements LifecycleListener {
   private final WorkQueue workQueue;
   private WorkQueue.Executor pool;
@@ -46,7 +47,7 @@
     }
   }
 
-  public ScheduledThreadPoolExecutor getPool() {
+  ScheduledThreadPoolExecutor getPool() {
     return this.pool;
   }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventStore.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventStore.java
index 58dbee2..a7785db 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventStore.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventStore.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -18,6 +18,7 @@
 
 import java.util.List;
 
+/** A store for change events to query. */
 public interface EventStore {
 
   /**
@@ -32,7 +33,7 @@
    *
    * @param query the query used to get events
    * @return a list of events in String format.
-   * @throws EventsLogException
+   * @throws EventsLogException if the given query can't be processed
    */
   List<String> queryChangeEvents(String query) throws EventsLogException;
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfig.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfig.java
index 0b31332..22287e6 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfig.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfig.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -14,6 +14,7 @@
 
 package com.ericsson.gerrit.plugins.eventslog;
 
+import com.google.common.base.Joiner;
 import com.google.gerrit.extensions.annotations.PluginName;
 import com.google.gerrit.server.config.PluginConfig;
 import com.google.gerrit.server.config.PluginConfigFactory;
@@ -24,9 +25,9 @@
 import java.nio.file.Path;
 import java.nio.file.Paths;
 
+/** Holder of all things related to events-log plugin configuration. */
 @Singleton
 public class EventsLogConfig {
-  static final String H2_DB_SUFFIX = ".h2.db";
   static final String CONFIG_COPY_LOCAL = "copyLocal";
   static final String CONFIG_MAX_AGE = "maxAge";
   static final String CONFIG_MAX_TRIES = "maxTries";
@@ -39,6 +40,7 @@
   static final String CONFIG_PASSWORD = "storePassword";
   static final String CONFIG_WAIT_TIME = "retryTimeout";
   static final String CONFIG_CONN_TIME = "connectTimeout";
+  static final String CONFIG_EVICT_IDLE_TIME = "evictIdleTime";
 
   static final boolean DEFAULT_COPY_LOCAL = false;
   static final int DEFAULT_MAX_AGE = 30;
@@ -48,25 +50,27 @@
   static final int DEFAULT_CONN_TIME = 1000;
   static final String DEFAULT_DRIVER = "org.h2.Driver";
   static final String DEFAULT_URL = "jdbc:h2:~/db/";
-  static String DEFAULT_LOCAL_PATH;
+  static final int DEFAULT_EVICT_IDLE_TIME = 1000 * 60;
 
-  private boolean copyLocal = DEFAULT_COPY_LOCAL;
-  private int maxAge = DEFAULT_MAX_AGE;
-  private int maxTries = DEFAULT_MAX_TRIES;
-  private int returnLimit = DEFAULT_RETURN_LIMIT;
-  private int waitTime = DEFAULT_WAIT_TIME;
-  private int connectTime = DEFAULT_CONN_TIME;
+  private boolean copyLocal;
+  private int maxAge;
+  private int maxTries;
+  private int returnLimit;
+  private int waitTime;
+  private int connectTime;
   private String storeDriver;
   private String storeUrl;
   private Path localStorePath;
   private String urlOptions;
   private String storeUsername;
   private String storePassword;
+  private int evictIdleTime;
 
   @Inject
-  public EventsLogConfig(PluginConfigFactory cfgFactory, SitePaths site,
+  EventsLogConfig(PluginConfigFactory cfgFactory,
+      SitePaths site,
       @PluginName String pluginName) {
-    DEFAULT_LOCAL_PATH = site.site_path.toString() + "/events-db/";
+    String defaultLocalPath = site.site_path.toString() + "/events-db/";
     PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName, true);
     copyLocal = cfg.getBoolean(CONFIG_COPY_LOCAL, DEFAULT_COPY_LOCAL);
     maxAge = cfg.getInt(CONFIG_MAX_AGE, DEFAULT_MAX_AGE);
@@ -76,10 +80,16 @@
     connectTime = cfg.getInt(CONFIG_CONN_TIME, DEFAULT_CONN_TIME);
     storeDriver = cfg.getString(CONFIG_DRIVER, DEFAULT_DRIVER);
     storeUrl = cfg.getString(CONFIG_URL, DEFAULT_URL);
-    localStorePath = Paths.get(cfg.getString(CONFIG_LOCAL_PATH, DEFAULT_LOCAL_PATH));
-    urlOptions = cfg.getString(CONFIG_URL_OPTIONS, "");
+    localStorePath = Paths.get(cfg.getString(CONFIG_LOCAL_PATH,
+        defaultLocalPath));
+    urlOptions = concatenate(cfg.getStringList(CONFIG_URL_OPTIONS));
     storeUsername = cfg.getString(CONFIG_USERNAME);
     storePassword = cfg.getString(CONFIG_PASSWORD);
+    evictIdleTime = cfg.getInt(CONFIG_EVICT_IDLE_TIME, DEFAULT_EVICT_IDLE_TIME);
+  }
+
+  private String concatenate(String[] stringList) {
+    return Joiner.on(";").join(stringList);
   }
 
   public int getMaxAge() {
@@ -133,4 +143,8 @@
   public boolean getCopyLocal() {
     return copyLocal;
   }
+
+  public int getEvictIdleTime() {
+    return evictIdleTime;
+  }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogException.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogException.java
index b332082..2137a95 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogException.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsLogException.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -17,27 +17,6 @@
 public class EventsLogException extends Exception {
   private static final long serialVersionUID = 1L;
 
-  public static final String MSG = "Error in events-log plugin";
-
-  /**
-   * Constructs a <code>EventsLogException</code> object with the default
-   * message.
-   */
-  public EventsLogException() {
-    super(MSG);
-  }
-
-  /**
-   * Constructs an <code>EventsLogException</code> object with the default
-   * message and a given <code>cause</code>.
-   *
-   * @param cause the underlying reason for this
-   *        <code>EventsLogException</code>
-   */
-  public EventsLogException(Throwable cause) {
-    super(MSG, cause);
-  }
-
   /**
    * Constructs an <code>EventsLogException</code> object with a given
    * <code>message</code>.
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServlet.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServlet.java
index 6bd0f91..121e2d8 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServlet.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServlet.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -34,9 +34,9 @@
 import javax.servlet.http.HttpServletResponse;
 
 @Singleton
-public class EventsRestApiServlet extends HttpServlet {
-  private static final Logger log = LoggerFactory
-      .getLogger(EventsRestApiServlet.class);
+class EventsRestApiServlet extends HttpServlet {
+  private static final Logger log =
+      LoggerFactory.getLogger(EventsRestApiServlet.class);
   private static final long serialVersionUID = 1L;
 
   private final EventStore store;
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/HttpModule.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/HttpModule.java
index a9dc0ba..a75eb73 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/HttpModule.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/HttpModule.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/MalformedQueryException.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/MalformedQueryException.java
index 5c7270d..56c0c73 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/MalformedQueryException.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/MalformedQueryException.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -16,8 +16,7 @@
 
 public class MalformedQueryException extends EventsLogException {
   private static final long serialVersionUID = 1L;
-
-  public static final String MESSAGE =
+  private static final String MESSAGE =
       "Query doesn't conform with the format required by the database";
 
   /**
@@ -38,26 +37,4 @@
   public MalformedQueryException(Throwable cause) {
     super(MESSAGE, cause);
   }
-
-  /**
-   * Constructs a <code>MalformedQueryException</code> object with a given
-   * <code>message</code>.
-   *
-   * @param message a description of the exception
-   */
-  public MalformedQueryException(String message) {
-    super(message);
-  }
-
-  /**
-   * Constructs a <code>MalformedQueryException</code> object with a given
-   * <code>message</code> and a given <code>cause</code>.
-   *
-   * @param message a description of the exception
-   * @param cause the underlying reason for this
-   *        <code>MalformedQueryException</code>
-   */
-  public MalformedQueryException(String message, Throwable cause) {
-    super(message, cause);
-  }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/QueryMaker.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/QueryMaker.java
index c1b823a..0fdf74c 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/QueryMaker.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/QueryMaker.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/ServiceUnavailableException.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/ServiceUnavailableException.java
index 9dcfe6f..57656e3 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/ServiceUnavailableException.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/ServiceUnavailableException.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -14,50 +14,17 @@
 
 package com.ericsson.gerrit.plugins.eventslog;
 
+/** An exception type for when the events database cannot be queried. */
 public class ServiceUnavailableException extends EventsLogException {
   private static final long serialVersionUID = 1L;
-
-  public static final String MESSAGE =
+  private static final String MESSAGE =
       "Database server disconnected, cannot query events";
 
   /**
-   * Constructs a <code>ServiceUnavailableException</code> object with the default
-   * message.
+   * Constructs a <code>ServiceUnavailableException</code> object with the
+   * default message.
    */
   public ServiceUnavailableException() {
     super(MESSAGE);
   }
-
-  /**
-   * Constructs a <code>ServiceUnavailableException</code> object with the default
-   * message and a given <code>cause</code>.
-   *
-   * @param cause the underlying reason for this
-   *        <code>ServiceUnavailableException</code>
-   */
-  public ServiceUnavailableException(Throwable cause) {
-    super(MESSAGE, cause);
-  }
-
-  /**
-   * Constructs a <code>ServiceUnavailableException</code> object with a given
-   * <code>message</code>.
-   *
-   * @param message a description of the exception
-   */
-  public ServiceUnavailableException(String message) {
-    super(message);
-  }
-
-  /**
-   * Constructs a <code>ServiceUnavailableException</code> object with a given
-   * <code>message</code> and a given <code>cause</code>.
-   *
-   * @param message a description of the exception
-   * @param cause the underlying reason for this
-   *        <code>ServiceUnavailableException</code>
-   */
-  public ServiceUnavailableException(String message, Throwable cause) {
-    super(message, cause);
-  }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/EventsDb.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/EventsDb.java
index 9b08bca..cf6d2d9 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/EventsDb.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/EventsDb.java
@@ -1,3 +1,17 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
 package com.ericsson.gerrit.plugins.eventslog.sql;
 
 import static java.lang.annotation.RetentionPolicy.RUNTIME;
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/LocalEventsDb.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/LocalEventsDb.java
index 157152d..0590d6e 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/LocalEventsDb.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/LocalEventsDb.java
@@ -1,3 +1,17 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
 package com.ericsson.gerrit.plugins.eventslog.sql;
 
 import static java.lang.annotation.RetentionPolicy.RUNTIME;
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLClient.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLClient.java
index e076522..6286f50 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLClient.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLClient.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -20,6 +20,9 @@
 import static com.ericsson.gerrit.plugins.eventslog.sql.SQLTable.PROJECT_ENTRY;
 import static com.ericsson.gerrit.plugins.eventslog.sql.SQLTable.TABLE_NAME;
 import static java.lang.String.format;
+import static java.util.concurrent.TimeUnit.DAYS;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
 
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ListMultimap;
@@ -41,211 +44,167 @@
 import java.sql.Timestamp;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.TimeUnit;
 
 class SQLClient {
   private static final Logger log = LoggerFactory.getLogger(SQLClient.class);
-
   private BasicDataSource ds;
-  private final Gson gson = new Gson();
 
   @Inject
   SQLClient(String storeDriver, String storeUrl, String urlOptions) {
     ds = new BasicDataSource();
     ds.setDriverClassName(storeDriver);
-    ds.setUrl(storeUrl + TABLE_NAME + ";" + urlOptions);
+    ds.setUrl(storeUrl);
+    ds.setConnectionProperties(urlOptions);
   }
 
   /**
-   * Set the username to connect to the database
-   * @param username
+   * Set the username to connect to the database.
+   *
+   * @param username the username as a string
    */
-  public void setUsername(String username) {
+  void setUsername(String username) {
     ds.setUsername(username);
   }
 
   /**
-   * Set the password to connect to the database
-   * @param password
+   * Set the password to connect to the database.
+   *
+   * @param password the password as a string
    */
-  public void setPassword(String password) {
+  void setPassword(String password) {
     ds.setPassword(password);
   }
 
   /**
+   * Set the time before an idle connection is evicted as well as the
+   * time between eviction runs.
+   *
+   * @param evictIdleTime the time in milliseconds before eviction
+   */
+  void setEvictIdleTime(int evictIdleTime) {
+    ds.setMinEvictableIdleTimeMillis(evictIdleTime);
+    ds.setTimeBetweenEvictionRunsMillis(evictIdleTime / 2);
+  }
+
+  /**
    * Create the database if it has not yet been created.
    *
-   * @throws SQLException
+   * @throws SQLException If there was a problem with the database
    */
-  public void createDBIfNotCreated() throws SQLException {
-    Connection conn = ds.getConnection();
-
-    StringBuilder query = new StringBuilder();
-    query.append(format("CREATE TABLE IF NOT EXISTS %s(", TABLE_NAME));
-    if (ds.getDriverClassName().contains("postgresql")) {
-      query.append(format("%s SERIAL PRIMARY KEY,", PRIMARY_ENTRY));
-    } else {
-      query.append(format("%s INT AUTO_INCREMENT PRIMARY KEY,", PRIMARY_ENTRY));
-    }
-    query.append(format("%s VARCHAR(255),", PROJECT_ENTRY));
-    query.append(format("%s TIMESTAMP DEFAULT NOW(),", DATE_ENTRY));
-    query.append(format("%s TEXT)", EVENT_ENTRY));
-
-    Statement stat = conn.createStatement();
-    try {
-      stat.execute(query.toString());
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
-    }
+  void createDBIfNotCreated() throws SQLException {
+    boolean postgresql = ds.getDriverClassName().contains("postgresql");
+    execute(SQLTable.createTableQuery(postgresql));
   }
 
   /**
    * Return if the database exists.
-   * @return true if it exist otherwise return false
-   * @throws SQLException
+   *
+   * @return true if it exists, otherwise return false
+   * @throws SQLException If there was a problem with the database
    */
-  public boolean dbExists() throws SQLException {
-    Connection conn = null;
-    ResultSet tables = null;
-    try {
-      conn = ds.getConnection();
-      tables =
-          conn.getMetaData().getTables(null, null, TABLE_NAME.toUpperCase(),
-              null);
+  boolean dbExists() throws SQLException {
+    try (Connection conn = ds.getConnection();
+        ResultSet tables =
+            conn.getMetaData().getTables(null, null, TABLE_NAME, null)) {
       return tables.next();
-    } finally {
-      closeResultSet(tables);
-      closeConnection(conn);
     }
   }
 
-  public void close() throws SQLException {
-    ds.close();
+  void close() {
+    try {
+      ds.close();
+    } catch (SQLException e) {
+      log.warn("Cannot close datasource", e);
+    }
   }
 
   /**
    * Get events as a multimap list of Strings and SQLEntries. The String
    * represents the project name, and the SQLEntry is the event information.
    *
-   * @param query
-   * @return multimap list of Strings (project names) and SQLEntries (events)
-   * @throws EventsLogException if there was an problem with the database
-   * @throws MalformedQueryException if there was a bad query request
+   * @param query the query as a string
+   * @return Multimap list of Strings (project names) and SQLEntries (events)
+   * @throws EventsLogException If there was a problem with the database
    */
-  public ListMultimap<String, SQLEntry> getEvents(String query)
+  ListMultimap<String, SQLEntry> getEvents(String query)
       throws EventsLogException {
-    Connection conn = null;
-    Statement stat = null;
-    try {
-      conn = ds.getConnection();
-      stat = conn.createStatement();
+    try (Connection conn = ds.getConnection();
+        Statement stat = conn.createStatement()) {
       return listEvents(stat, query);
     } catch (SQLException e) {
       throw new EventsLogException("Cannot query database", e);
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
     }
   }
 
   /**
-   * Store the event in the database
+   * Store the event in the database.
    *
    * @param event The event to store
    * @throws SQLException If there was a problem with the database
    */
-  public void storeEvent(ProjectEvent event) throws SQLException {
-    String json = gson.toJson(event);
-    Connection conn = ds.getConnection();
-    Statement stat = conn.createStatement();
-    try {
-      stat.execute(format("INSERT INTO %s(%s, %s, %s) ", TABLE_NAME,
-          PROJECT_ENTRY, DATE_ENTRY, EVENT_ENTRY)
-          + format("VALUES('%s', '%s', '%s')", event.getProjectNameKey().get(),
-              new Timestamp(TimeUnit.SECONDS.toMillis(event.eventCreatedOn)), json));
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
-    }
+  void storeEvent(ProjectEvent event) throws SQLException {
+    storeEvent(event.getProjectNameKey().get(),
+        new Timestamp(SECONDS.toMillis(event.eventCreatedOn)),
+        new Gson().toJson(event));
+
   }
 
   /**
-   * Store the event in the database
+   * Store the event in the database.
    *
    * @param projectName The project in which this event happened
    * @param timestamp The time at which this event took place
    * @param event The event as a string
    * @throws SQLException If there was a problem with the database
    */
-  public void storeEvent(String projectName, Timestamp timestamp, String event)
+  void storeEvent(String projectName, Timestamp timestamp, String event)
       throws SQLException {
-    Connection conn = ds.getConnection();
-    Statement stat = conn.createStatement();
-    try {
-      stat.execute(format("INSERT INTO %s(%s, %s, %s) ", TABLE_NAME,
-          PROJECT_ENTRY, DATE_ENTRY, EVENT_ENTRY)
-          + format("VALUES('%s', '%s', '%s')", projectName, timestamp, event));
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
-    }
+    execute(format("INSERT INTO %s(%s, %s, %s) ", TABLE_NAME, PROJECT_ENTRY,
+        DATE_ENTRY, EVENT_ENTRY)
+        + format("VALUES('%s', '%s', '%s')", projectName, timestamp, event));
   }
 
   /**
-   * Remove all events that are older than maxAge
+   * Remove all events that are older than maxAge.
    *
    * @param maxAge The maximum age to keep events
-   * @throws SQLException If there was a problem with the database
    */
-  public void removeOldEvents(int maxAge) throws SQLException {
-    Connection conn = ds.getConnection();
-    Statement stat = conn.createStatement();
+  void removeOldEvents(int maxAge) {
     try {
-      stat.execute(format("DELETE FROM %s WHERE %s < '%s'", TABLE_NAME,
-          DATE_ENTRY, new Timestamp(System.currentTimeMillis()
-              - TimeUnit.MILLISECONDS.convert(maxAge, TimeUnit.DAYS))));
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
+      execute(format(
+          "DELETE FROM %s WHERE %s < '%s'",
+          TABLE_NAME,
+          DATE_ENTRY,
+          new Timestamp(System.currentTimeMillis()
+              - MILLISECONDS.convert(maxAge, DAYS))));
+    } catch (SQLException e) {
+      log.warn("Cannot remove old event entries from database", e);
     }
   }
 
   /**
-   * Remove all events corresponding to this project
+   * Remove all events corresponding to this project.
    *
    * @param project Events attributed to this project should be removed
-   * @throws SQLException If there was a problem with the database
    */
-  public void removeProjectEvents(String project) throws SQLException {
-    Connection conn = ds.getConnection();
-    Statement stat = conn.createStatement();
+  void removeProjectEvents(String project) {
     try {
-      stat.execute(String.format("DELETE FROM %s WHERE project = '%s'",
-          TABLE_NAME, project));
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
+      execute(
+          format("DELETE FROM %s WHERE project = '%s'", TABLE_NAME, project));
+    } catch (SQLException e) {
+      log.warn(
+          "Cannot remove project " + project + " events from database", e);
     }
   }
 
   /**
-   * Do a simple query on the database. This is used to determine whether or not
-   * the main database is online.
+   * Do a simple query on the database. This is used to determine whether or
+   * not the main database is online.
    *
    * @throws SQLException If there was a problem with the database
    */
-  public void queryOne() throws SQLException {
-    Connection conn = null;
-    Statement stat = null;
-    try {
-      conn = ds.getConnection();
-      stat = conn.createStatement();
-      stat.executeQuery("SELECT * FROM " + TABLE_NAME + " LIMIT 1");
-    } finally {
-      closeStatement(stat);
-      closeConnection(conn);
-    }
+  void queryOne() throws SQLException {
+    execute("SELECT * FROM " + TABLE_NAME + " LIMIT 1");
   }
 
   /**
@@ -254,33 +213,23 @@
    * @return List of all events retrieved from the database
    * @throws SQLException If there was a problem with the database
    */
-  public List<SQLEntry> getAll() throws SQLException {
+  List<SQLEntry> getAll() throws SQLException {
     List<SQLEntry> entries = new ArrayList<>();
-    Connection conn = null;
-    Statement stat = null;
-    ResultSet rs = null;
-    try {
-      conn = ds.getConnection();
-      stat = conn.createStatement();
-      rs = stat.executeQuery("SELECT * FROM " + TABLE_NAME);
+    try (Connection conn = ds.getConnection();
+        Statement stat = conn.createStatement();
+        ResultSet rs = stat.executeQuery("SELECT * FROM " + TABLE_NAME)) {
       while (rs.next()) {
         entries.add(new SQLEntry(rs.getString(PROJECT_ENTRY), rs
             .getTimestamp(DATE_ENTRY), rs.getString(EVENT_ENTRY), rs
             .getInt(PRIMARY_ENTRY)));
       }
       return entries;
-    } finally {
-      closeResultSet(rs);
-      closeStatement(stat);
-      closeConnection(conn);
     }
   }
 
   private ListMultimap<String, SQLEntry> listEvents(Statement stat, String query)
       throws MalformedQueryException {
-    ResultSet rs = null;
-    try {
-      rs = stat.executeQuery(query);
+    try (ResultSet rs = stat.executeQuery(query)) {
       ListMultimap<String, SQLEntry> result = ArrayListMultimap.create();
       while (rs.next()) {
         SQLEntry entry =
@@ -292,38 +241,13 @@
       return result;
     } catch (SQLException e) {
       throw new MalformedQueryException(e);
-    } finally {
-      closeResultSet(rs);
     }
   }
 
-  private void closeResultSet(ResultSet resultSet) {
-    if (resultSet != null) {
-      try {
-        resultSet.close();
-      } catch (SQLException e) {
-        log.warn("Cannot close result set", e);
-      }
-    }
-  }
-
-  private void closeStatement(Statement stat) {
-    if (stat != null) {
-      try {
-        stat.close();
-      } catch (SQLException e) {
-        log.warn("Cannot close statement", e);
-      }
-    }
-  }
-
-  private void closeConnection(Connection conn) {
-    if (conn != null) {
-      try {
-        conn.close();
-      } catch (SQLException e) {
-        log.warn("Cannot close connection", e);
-      }
+  private void execute(String query) throws SQLException {
+    try (Connection conn = ds.getConnection();
+        Statement stat = conn.createStatement()) {
+      stat.execute(query);
     }
   }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntry.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntry.java
index a97dc1a..1ae9228 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntry.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntry.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -17,6 +17,7 @@
 import java.sql.Timestamp;
 
 class SQLEntry implements Comparable<SQLEntry> {
+  private static final int SEED = 31;
   private String name;
   private Timestamp timestamp;
   private String event;
@@ -43,19 +44,22 @@
 
   @Override
   public int compareTo(SQLEntry o) {
-    return this.id - o.id;
+    return Integer.compare(this.id, o.id);
   }
 
   @Override
   public boolean equals(Object o) {
+    if (o == null) {
+      return false;
+    }
+    if (this.getClass() != o.getClass()) {
+      return false;
+    }
     return this.id == ((SQLEntry) o).id;
   }
 
   @Override
   public int hashCode() {
-    final int prime = 31;
-    int result = 1;
-    result = prime * result + id;
-    return result;
+    return SEED + id;
   }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLModule.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLModule.java
index 40f26ea..32572e3 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLModule.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLModule.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -42,11 +42,11 @@
   @Singleton
   @EventsDb
   SQLClient provideSqlClient(EventsLogConfig cfg) {
-    SQLClient sqlClient =
-        new SQLClient(cfg.getStoreDriver(), cfg.getStoreUrl(),
-            cfg.getUrlOptions());
+    SQLClient sqlClient = new SQLClient(cfg.getStoreDriver(), cfg.getStoreUrl(),
+        cfg.getUrlOptions());
     sqlClient.setUsername(cfg.getStoreUsername());
     sqlClient.setPassword(cfg.getStorePassword());
+    sqlClient.setEvictIdleTime(cfg.getEvictIdleTime());
     return sqlClient;
   }
 
@@ -56,7 +56,9 @@
   SQLClient provideLocalSqlClient(EventsLogConfig cfg) {
     String path = cfg.getLocalStorePath().toString();
     path = path.endsWith("/") ? path : path + "/";
-    return new SQLClient(cfg.getLocalStoreDriver(), H2_DB_PREFIX
-        + path, cfg.getUrlOptions());
+    SQLClient sqlClient = new SQLClient(cfg.getLocalStoreDriver(),
+        H2_DB_PREFIX + path + SQLTable.TABLE_NAME, cfg.getUrlOptions());
+    sqlClient.setEvictIdleTime(cfg.getEvictIdleTime());
+    return sqlClient;
   }
 }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLQueryMaker.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLQueryMaker.java
index a3aa4ad..93c6569 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLQueryMaker.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLQueryMaker.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -34,23 +34,31 @@
 
 @Singleton
 class SQLQueryMaker implements QueryMaker {
+  private static final int TWO = 2;
   private static final String TIME_ONE = "t1";
   private static final String TIME_TWO = "t2";
-  private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat(
-      "yyyy-MM-dd HH:mm:ss");
-  private static final DateFormat DATE_ONLY_FORMAT = new SimpleDateFormat(
-      "yyyy-MM-dd");
+  private static final ThreadLocal<DateFormat> DATE_TIME_FORMAT =
+      new ThreadLocal<DateFormat>() {
+        @Override
+        protected DateFormat initialValue() {
+          return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        }
+      };
+  private static final ThreadLocal<DateFormat> DATE_ONLY_FORMAT =
+      new ThreadLocal<DateFormat>() {
+        @Override
+        protected DateFormat initialValue() {
+          return new SimpleDateFormat("yyyy-MM-dd");
+        }
+      };
 
   private final int returnLimit;
 
   @Inject
-  public SQLQueryMaker(EventsLogConfig config) {
+  SQLQueryMaker(EventsLogConfig config) {
     this.returnLimit = config.getReturnLimit();
   }
 
-  /**
-   * {@inheritDoc}
-   */
   @Override
   public String formQueryFromRequestParameters(Map<String, String> params)
       throws MalformedQueryException {
@@ -65,13 +73,10 @@
     }
     return String.format(
         "SELECT * FROM %s WHERE %s BETWEEN '%s' and '%s' LIMIT %d", TABLE_NAME,
-        DATE_ENTRY, DATE_TIME_FORMAT.format(dates[0]),
-        DATE_TIME_FORMAT.format(dates[1]), returnLimit);
+        DATE_ENTRY, DATE_TIME_FORMAT.get().format(dates[0]),
+        DATE_TIME_FORMAT.get().format(dates[1]), returnLimit);
   }
 
-  /**
-   * {@inheritDoc}
-   */
   @Override
   public String getDefaultQuery() {
     return "SELECT * FROM(SELECT * FROM " + TABLE_NAME
@@ -85,7 +90,7 @@
     if (dateOne == null & dateTwo == null) {
       throw new MalformedQueryException();
     }
-    Date[] dates = new Date[2];
+    Date[] dates = new Date[TWO];
     Date dOne =
         dateOne == null && dateTwo != null ? cal.getTime() : parseDate(dateOne);
     Date dTwo =
@@ -98,9 +103,9 @@
   private Date parseDate(String date) throws ParseException {
     Date parsedDate;
     try {
-      parsedDate = DATE_TIME_FORMAT.parse(date);
+      parsedDate = DATE_TIME_FORMAT.get().parse(date);
     } catch (ParseException e) {
-      parsedDate = DATE_ONLY_FORMAT.parse(date);
+      parsedDate = DATE_ONLY_FORMAT.get().parse(date);
     }
     return parsedDate;
   }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStore.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStore.java
index bb5412c..0699160 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStore.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStore.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -32,7 +32,6 @@
 import com.ericsson.gerrit.plugins.eventslog.EventStore;
 import com.ericsson.gerrit.plugins.eventslog.EventsLogConfig;
 import com.ericsson.gerrit.plugins.eventslog.EventsLogException;
-import com.ericsson.gerrit.plugins.eventslog.MalformedQueryException;
 import com.ericsson.gerrit.plugins.eventslog.ServiceUnavailableException;
 
 import org.slf4j.Logger;
@@ -55,7 +54,7 @@
 @Singleton
 class SQLStore implements EventStore, LifecycleListener {
   private static final Logger log = LoggerFactory.getLogger(SQLStore.class);
-  public static final String H2_DB_SUFFIX = ".h2.db";
+  private static final String H2_DB_SUFFIX = ".h2.db";
 
   private final ProjectControl.GenericFactory projectControlFactory;
   private final Provider<CurrentUser> userProvider;
@@ -68,7 +67,7 @@
   private boolean online = true;
   private boolean copyLocal;
   private final ScheduledThreadPoolExecutor pool;
-  private ScheduledFuture<?> task;
+  private ScheduledFuture<?> checkConnTask;
   private Path localPath;
 
   @Inject
@@ -77,7 +76,7 @@
       EventsLogConfig cfg,
       @EventsDb SQLClient eventsDb,
       @LocalEventsDb SQLClient localEventsDb,
-      @EventPool ScheduledThreadPoolExecutor pool ) {
+      @EventPool ScheduledThreadPoolExecutor pool) {
     this.maxAge = cfg.getMaxAge();
     this.maxTries = cfg.getMaxTries();
     this.waitTime = cfg.getWaitTime();
@@ -98,26 +97,15 @@
 
   @Override
   public void stop() {
-    if (task != null) {
-      task.cancel(true);
-    }
-    try {
-      eventsDb.close();
-    } catch (SQLException e) {
-      log.warn("Cannot close datasource ", e);
-    }
-    try {
-      localEventsDb.close();
-    } catch (SQLException e) {
-      log.warn("Cannot close datasource ", e);
-    }
+    cancelCheckConnectionTaskIfScheduled(true);
+    eventsDb.close();
+    localEventsDb.close();
   }
 
   /**
    * {@inheritDoc}
-   * The events returned are restricted to the projects which are visible to the
-   * user.
-   * @throws MalformedQueryException if the given query can't be processed
+   * The events returned are restricted to the projects which are visible to
+   * the user.
    * @throws ServiceUnavailableException if working in offline mode
    */
   @Override
@@ -125,27 +113,31 @@
     if (!online) {
       throw new ServiceUnavailableException();
     }
-    List<String> events = new ArrayList<>();
     List<SQLEntry> entries = new ArrayList<>();
     Project.NameKey project = null;
-    for (Entry<String, Collection<SQLEntry>> entry : eventsDb.getEvents(query)
-        .asMap().entrySet()) {
+    for (Entry<String, Collection<SQLEntry>> entry
+        : eventsDb.getEvents(query).asMap().entrySet()) {
       try {
         project = new Project.NameKey(entry.getKey());
-        if (projectControlFactory.controlFor(project, userProvider.get())
-            .isVisible()) {
+        if (projectControlFactory.controlFor(project,
+            userProvider.get()).isVisible()) {
           entries.addAll(entry.getValue());
         }
       } catch (NoSuchProjectException e) {
         log.warn("Database contains a non-existing project, " + project.get()
-            + ", removing project from database", e);
-        removeProjectEvents(project.get());
+            + ", removing project from database");
+        eventsDb.removeProjectEvents(project.get());
       } catch (IOException e) {
         log.warn("Cannot get project visibility info for " + project.get()
             + " from cache", e);
       }
     }
+    return sortedEventsFromEntries(entries);
+  }
+
+  private List<String> sortedEventsFromEntries(List<SQLEntry> entries) {
     Collections.sort(entries);
+    List<String> events = new ArrayList<>();
     for (SQLEntry entry : entries) {
       events.add(entry.getEvent());
     }
@@ -200,66 +192,43 @@
     try {
       getEventsDb().createDBIfNotCreated();
     } catch (SQLException e) {
-      log.warn("Cannot start the database. Events will be stored locally "
-          + "until database connection can be established", e);
+      log.warn("Cannot start the database. Events will be stored locally"
+          + " until database connection can be established", e);
       setOnline(false);
     }
     if (online) {
       restoreEventsFromLocal();
     }
-    removeOldEvents();
-  }
-
-  private void removeOldEvents() {
-    try {
-      getEventsDb().removeOldEvents(maxAge);
-    } catch (SQLException e) {
-      log.warn("Cannot remove old entries from database", e);
-    }
+    getEventsDb().removeOldEvents(maxAge);
   }
 
   private SQLClient getEventsDb() {
     return online ? eventsDb : localEventsDb;
   }
 
-  private void removeProjectEvents(String project) {
-    try {
-      eventsDb.removeProjectEvents(project);
-    } catch (SQLException e) {
-      log.warn("Cannot remove project " + project + " from database", e);
-    }
-  }
-
   private void setOnline(boolean online) {
     this.online = online;
     setUp();
     if (!online) {
-      task = pool.scheduleWithFixedDelay(
+      checkConnTask = pool.scheduleWithFixedDelay(
           new CheckConnectionTask(), 0, connectTime, TimeUnit.MILLISECONDS);
     } else {
-      if (task != null) {
-        task.cancel(false);
-      }
+      cancelCheckConnectionTaskIfScheduled(false);
+    }
+  }
+
+  private void cancelCheckConnectionTaskIfScheduled(boolean mayInterrupt) {
+    if (checkConnTask != null) {
+      checkConnTask.cancel(mayInterrupt);
     }
   }
 
   private void restoreEventsFromLocal() {
-
-    boolean localDbExists = false;
-    try {
-      localDbExists = localEventsDb.dbExists();
-    } catch (SQLException e) {
-      log.warn(
-          "Could not check existence of local database, assume that it doesn't exist",
-          e);
-    }
-    if (!localDbExists) {
+    if (!localDbExists()) {
       return;
     }
-
-    List<SQLEntry> entries;
     try {
-      entries = localEventsDb.getAll();
+      List<SQLEntry> entries = localEventsDb.getAll();
       if (entries.isEmpty()) {
         log.debug("No events to restore from local");
         return;
@@ -270,14 +239,8 @@
     } catch (SQLException e) {
       log.warn("Could not query all events from local", e);
     }
-    try {
-      if (copyLocal) {
-        copyFile();
-      }
-      localEventsDb.removeOldEvents(0);
-    } catch (SQLException e) {
-      log.warn("Could not destroy local database", e);
-    }
+    copyFile(copyLocal);
+    localEventsDb.removeOldEvents(0);
   }
 
   private void restoreEvent(SQLEntry entry) {
@@ -289,17 +252,6 @@
     }
   }
 
-  private boolean checkConnection() {
-    log.info("Checking database connection...");
-    try {
-      eventsDb.queryOne();
-      return true;
-    } catch (SQLException e) {
-      log.debug("Problem checking database connection", e);
-      return false;
-    }
-  }
-
   class CheckConnectionTask implements Runnable {
     CheckConnectionTask() {
     }
@@ -316,14 +268,39 @@
     public String toString() {
       return "(Events-log) Connect to database";
     }
+
+    private boolean checkConnection() {
+      log.info("Checking database connection...");
+      try {
+        eventsDb.queryOne();
+        return true;
+      } catch (SQLException e) {
+        log.debug("Problem checking database connection", e);
+        return false;
+      }
+    }
   }
 
-  private void copyFile() {
+  private boolean localDbExists() {
+    boolean exists = false;
+    try {
+      exists = localEventsDb.dbExists();
+    } catch (SQLException e) {
+      log.warn(
+          "Could not check existence of local database, assume that it doesn't exist",
+          e);
+    }
+    return exists;
+  }
+
+  private void copyFile(boolean copyLocal) {
+    if (!copyLocal) {
+      return;
+    }
     File file = localPath.resolve(TABLE_NAME + H2_DB_SUFFIX).toFile();
-    File copyFile =
-        localPath.resolve(
-            TABLE_NAME + (TimeUnit.MILLISECONDS.toSeconds(TimeUtil.nowMs()))
-                + H2_DB_SUFFIX).toFile();
+    File copyFile = localPath.resolve(TABLE_NAME
+        + (TimeUnit.MILLISECONDS.toSeconds(TimeUtil.nowMs()))
+        + H2_DB_SUFFIX).toFile();
     try {
       Files.copy(file, copyFile);
     } catch (IOException e) {
diff --git a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLTable.java b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLTable.java
index 5464f9f..8102b1b 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLTable.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLTable.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -14,13 +14,29 @@
 
 package com.ericsson.gerrit.plugins.eventslog.sql;
 
+import static java.lang.String.format;
+
 final class SQLTable {
-  protected static final String TABLE_NAME = "ChangeEvents";
-  protected static final String PRIMARY_ENTRY = "id";
-  protected static final String PROJECT_ENTRY = "project";
-  protected static final String DATE_ENTRY = "date_created";
-  protected static final String EVENT_ENTRY = "event_info";
+  static final String TABLE_NAME = "ChangeEvents";
+  static final String PRIMARY_ENTRY = "id";
+  static final String PROJECT_ENTRY = "project";
+  static final String DATE_ENTRY = "date_created";
+  static final String EVENT_ENTRY = "event_info";
 
   private SQLTable() {
   }
+
+  static String createTableQuery(boolean postgresql) {
+    StringBuilder query = new StringBuilder();
+    query.append(format("CREATE TABLE IF NOT EXISTS %s(", TABLE_NAME));
+    if (postgresql) {
+      query.append(format("%s SERIAL PRIMARY KEY,", PRIMARY_ENTRY));
+    } else {
+      query.append(format("%s INT AUTO_INCREMENT PRIMARY KEY,", PRIMARY_ENTRY));
+    }
+    query.append(format("%s VARCHAR(255),", PROJECT_ENTRY));
+    query.append(format("%s TIMESTAMP DEFAULT NOW(),", DATE_ENTRY));
+    query.append(format("%s TEXT)", EVENT_ENTRY));
+    return query.toString();
+  }
 }
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
index cc7f50e..749c600 100644
--- a/src/main/resources/Documentation/config.md
+++ b/src/main/resources/Documentation/config.md
@@ -4,12 +4,15 @@
 File 'gerrit.config'
 --------------------
 
+```
   [plugin "@PLUGIN@"]
     maxAge = 20
     returnLimit = 10000
     storeUrl = jdbc:h2:~/gerrit/db/
-    urlOptions = DB_CLOSE_DELAY=10
+    urlOptions = loglevel=INFO
+    urlOptions = logUnclosedConnections=true
     copyLocal = true
+```
 
 plugin.@PLUGIN@.maxAge
 :    Specify the maximum allowed age in days of the entries in the database.
@@ -41,7 +44,10 @@
      also be defined in secure.config.
 
 plugin.@PLUGIN@.urlOptions
-:    Options to append to the database url.
+:    Options to append to the database url. Each option should be specified in a
+     separate line using the option=value format. For example:
+       urlOptions = loglevel=INFO
+       urlOptions = logUnclosedConnections=true
 
 plugin.@PLUGIN@.maxTries
 :    Maximum number of times the plugin should attempt to store the event if a
@@ -63,4 +69,9 @@
      restored, set to true. The file will be copied to the same location as the
      backup database with a timestamp appended. Note that the copied file will
      not be deleted and must be removed manually. When not specified, the default
-     value is set to false.
\ No newline at end of file
+     value is set to false.
+
+plugin.@PLUGIN@.evictIdleTime
+:    Interval of time in milliseconds after which an idle database connection is
+     evicted from the connection pool. When not specified, the default value is
+     set to 60000ms.
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventHandlerTest.java
index 730b022..67ff28b 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventHandlerTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventHandlerTest.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfigTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfigTest.java
index 8f66084..9388319 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfigTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsLogConfigTest.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2015 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -16,6 +16,7 @@
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_CONN_TIME;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_COPY_LOCAL;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_DRIVER;
+import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_EVICT_IDLE_TIME;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_LOCAL_PATH;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_MAX_AGE;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.CONFIG_MAX_TRIES;
@@ -28,6 +29,7 @@
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_CONN_TIME;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_COPY_LOCAL;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_DRIVER;
+import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_EVICT_IDLE_TIME;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_MAX_AGE;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_MAX_TRIES;
 import static com.ericsson.gerrit.plugins.eventslog.EventsLogConfig.DEFAULT_RETURN_LIMIT;
@@ -36,6 +38,7 @@
 import static com.google.common.truth.Truth.assertThat;
 import static org.easymock.EasyMock.expect;
 
+import com.google.common.base.Joiner;
 import com.google.gerrit.server.config.PluginConfig;
 import com.google.gerrit.server.config.PluginConfigFactory;
 import com.google.gerrit.server.config.SitePaths;
@@ -47,7 +50,8 @@
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 
-import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.Files;
 
 public class EventsLogConfigTest {
   private SitePaths site;
@@ -57,15 +61,18 @@
   private EasyMockSupport easyMock;
   private String defaultLocalStorePath;
   private String localStorePath;
+  private String [] urlOptions = new String[]{"a=b", "c=d"};
+
+  private static final int CUSTOM_EVICT_IDLE_TIME = 10000;
 
   @Rule
   public TemporaryFolder gerrit_site = new TemporaryFolder();
 
   @Before
-  public void setUp() throws FileNotFoundException {
+  public void setUp() throws IOException {
     easyMock = new EasyMockSupport();
-    site = new SitePaths(gerrit_site.getRoot());
-    site.etc_dir.mkdirs();
+    site = new SitePaths(gerrit_site.getRoot().toPath());
+    Files.createDirectories(site.etc_dir);
     defaultLocalStorePath = site.site_path.toString() + "/events-db/";
     configMock = easyMock.createMock(PluginConfig.class);
     cfgFactoryMock = easyMock.createMock(PluginConfigFactory.class);
@@ -83,9 +90,10 @@
     expect(configMock.getString(CONFIG_DRIVER, DEFAULT_DRIVER)).andReturn(DEFAULT_DRIVER);
     expect(configMock.getString(CONFIG_URL, DEFAULT_URL)).andReturn(DEFAULT_URL);
     expect(configMock.getString(CONFIG_LOCAL_PATH, defaultLocalStorePath)).andReturn(defaultLocalStorePath);
-    expect(configMock.getString(CONFIG_URL_OPTIONS, "")).andReturn("");
+    expect(configMock.getStringList(CONFIG_URL_OPTIONS)).andReturn(new String[0]);
     expect(configMock.getString(CONFIG_USERNAME)).andReturn(null);
     expect(configMock.getString(CONFIG_PASSWORD)).andReturn(null);
+    expect(configMock.getInt(CONFIG_EVICT_IDLE_TIME, DEFAULT_EVICT_IDLE_TIME)).andReturn(DEFAULT_EVICT_IDLE_TIME);
 
     easyMock.replayAll();
   }
@@ -101,9 +109,10 @@
     expect(configMock.getString(CONFIG_DRIVER, DEFAULT_DRIVER)).andReturn("org.h2.Driver2");
     expect(configMock.getString(CONFIG_URL, DEFAULT_URL)).andReturn("jdbc:h2:~/gerrit/db");
     expect(configMock.getString(CONFIG_LOCAL_PATH, defaultLocalStorePath)).andReturn(localStorePath);
-    expect(configMock.getString(CONFIG_URL_OPTIONS, "")).andReturn("DB_CLOSE_DELAY=10");
+    expect(configMock.getStringList(CONFIG_URL_OPTIONS)).andReturn(urlOptions);
     expect(configMock.getString(CONFIG_USERNAME)).andReturn("testUsername");
     expect(configMock.getString(CONFIG_PASSWORD)).andReturn("testPassword");
+    expect(configMock.getInt(CONFIG_EVICT_IDLE_TIME, DEFAULT_EVICT_IDLE_TIME)).andReturn(CUSTOM_EVICT_IDLE_TIME);
 
     easyMock.replayAll();
   }
@@ -125,6 +134,7 @@
     assertThat(config.getUrlOptions()).isEmpty();
     assertThat(config.getStoreUsername()).isNull();
     assertThat(config.getStorePassword()).isNull();
+    assertThat(config.getEvictIdleTime()).isEqualTo(DEFAULT_EVICT_IDLE_TIME);
   }
 
   @Test
@@ -141,8 +151,9 @@
     assertThat(config.getLocalStorePath().toString() + "/").isEqualTo(localStorePath);
     assertThat(config.getStoreDriver()).isEqualTo("org.h2.Driver2");
     assertThat(config.getStoreUrl()).isEqualTo("jdbc:h2:~/gerrit/db");
-    assertThat(config.getUrlOptions()).isEqualTo("DB_CLOSE_DELAY=10");
+    assertThat(config.getUrlOptions()).isEqualTo(Joiner.on(";").join(urlOptions));
     assertThat(config.getStoreUsername()).isEqualTo("testUsername");
     assertThat(config.getStorePassword()).isEqualTo("testPassword");
+    assertThat(config.getEvictIdleTime()).isEqualTo(CUSTOM_EVICT_IDLE_TIME);
   }
 }
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServletTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServletTest.java
index 3321469..2e51106 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServletTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/EventsRestApiServletTest.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -15,6 +15,7 @@
 package com.ericsson.gerrit.plugins.eventslog;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.easymock.EasyMock.newCapture;
 import static org.easymock.EasyMock.capture;
 import static org.easymock.EasyMock.expect;
 import static org.easymock.EasyMock.expectLastCall;
@@ -73,7 +74,7 @@
     Map<String, String> paramMock = new HashMap<>();
     paramMock.put("a", "1");
     paramMock.put("b", "2");
-    Capture<Map<String, String>> catcher = new Capture<>();
+    Capture<Map<String, String>> catcher = newCapture();
     easyMock.resetAll();
     expect(userProviderMock.get()).andStubReturn(userMock);
     expect(userMock.isIdentifiedUser()).andStubReturn(true);
@@ -91,7 +92,7 @@
   @Test
   public void badQueryString() throws Exception {
     String queryStringMock = "a;b";
-    Capture<Map<String, String>> catcher = new Capture<>();
+    Capture<Map<String, String>> catcher = newCapture();
     easyMock.resetAll();
     expect(userProviderMock.get()).andStubReturn(userMock);
     expect(userMock.isIdentifiedUser()).andStubReturn(true);
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/QueryMakerTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/QueryMakerTest.java
index 090d2c4..bad6ccf 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/QueryMakerTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/QueryMakerTest.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntryTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntryTest.java
new file mode 100644
index 0000000..eee066b
--- /dev/null
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLEntryTest.java
@@ -0,0 +1,78 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.ericsson.gerrit.plugins.eventslog.sql;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.sql.Timestamp;
+import java.util.Calendar;
+
+public class SQLEntryTest {
+
+  private static final long NOW = Calendar.getInstance().getTimeInMillis();
+  private SQLEntry entry1;
+  private SQLEntry entry2;
+  private SQLEntry entry3;
+  private SQLEntry entry4;
+
+  @Before
+  public void setUp() {
+    Timestamp timestamp = new Timestamp(NOW);
+    entry1 = new SQLEntry("name1", timestamp, "event1", Integer.MAX_VALUE);
+    entry2 = new SQLEntry("name2", timestamp, "event2", Integer.MIN_VALUE);
+    entry3 = new SQLEntry("name3", timestamp, "event3", 0);
+    entry4 = new SQLEntry("name4", timestamp, "event4", Integer.MAX_VALUE);
+  }
+
+  @Test
+  public void testHashCode() throws Exception {
+    assertThat(entry1.hashCode()).isEqualTo(-2147483618);
+    assertThat(entry2.hashCode()).isEqualTo(-2147483617);
+    assertThat(entry3.hashCode()).isEqualTo(31);
+  }
+
+  @Test
+  public void testGetName() throws Exception {
+    assertThat(entry1.getName()).isEqualTo("name1");
+  }
+
+  @Test
+  public void testGetTimestamp() throws Exception {
+    assertThat(entry1.getTimestamp()).isEqualTo(new Timestamp(NOW));
+  }
+
+  @Test
+  public void testGetEvent() throws Exception {
+    assertThat(entry1.getEvent()).isEqualTo("event1");
+  }
+
+  @Test
+  public void testCompareTo() throws Exception {
+    assertThat(entry1.compareTo(entry2)).isEqualTo(1);
+    assertThat(entry2.compareTo(entry1)).isEqualTo(-1);
+  }
+
+  @Test
+  public void testEquals() throws Exception {
+    assertThat(entry1.equals(null)).isFalse();
+    assertThat(entry1.equals("String object")).isFalse();
+    assertThat(entry1.equals(entry1)).isTrue();
+    assertThat(entry1.equals(entry2)).isFalse();
+    assertThat(entry1.equals(entry4)).isTrue();
+  }
+}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStoreTest.java b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStoreTest.java
index 9767c58..ebc18e4 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStoreTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/eventslog/sql/SQLStoreTest.java
@@ -1,6 +1,6 @@
 // Copyright (C) 2014 The Android Open Source Project
 //
-// Licensed under the Apache License, Version 2.0 (the "License"),
+// Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 //
@@ -59,10 +59,10 @@
 
 public class SQLStoreTest {
   private static final Logger log = LoggerFactory.getLogger(SQLStoreTest.class);
-  private static final String TEST_URL = "jdbc:h2:mem:";
+  private static final String TEST_URL = "jdbc:h2:mem:" + TABLE_NAME;
   private static final String TEST_LOCAL_URL = "jdbc:h2:mem:test:";
   private static final String TEST_DRIVER = "org.h2.Driver";
-  private static final String TEST_OPTIONS = "DB_CLOSE_DELAY=-1";
+  private static final String TEST_OPTIONS = "DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
   private static final String TERM_CONN_MSG = "terminating connection";
   private static final String MSG = "message";
   private static final String GENERIC_QUERY = "SELECT * FROM " + TABLE_NAME;
@@ -76,7 +76,7 @@
   private SQLStore store;
   private ScheduledThreadPoolExecutor poolMock;
 
-  private String path = TEST_URL + TABLE_NAME + ";" + TEST_OPTIONS;
+  private String path = TEST_URL + ";" + TEST_OPTIONS;
   private Connection conn;
   private Statement stat;
   private List<SQLEntry> results;
@@ -302,11 +302,14 @@
     NoSuchProjectException e =
         easyMock.createNiceMock(NoSuchProjectException.class);
     expect(
-        pcFactoryMock.controlFor(EasyMock.anyObject(Project.NameKey.class),
-            EasyMock.anyObject(CurrentUser.class))).andReturn(pc).times(2);
+        pcFactoryMock.controlFor(EasyMock.eq(mockEvent.getProjectNameKey()),
+            EasyMock.anyObject(CurrentUser.class))).andReturn(pc).once();
+    expect(
+        pcFactoryMock.controlFor(EasyMock.eq(mockEvent2.getProjectNameKey()),
+            EasyMock.anyObject(CurrentUser.class))).andReturn(pc).once();
     expect(pc.isVisible()).andReturn(true).times(2);
     expect(
-        pcFactoryMock.controlFor(EasyMock.anyObject(Project.NameKey.class),
+        pcFactoryMock.controlFor(EasyMock.eq(mockEvent3.getProjectNameKey()),
             EasyMock.anyObject(CurrentUser.class))).andThrow(e);
     easyMock.replayAll();