View Javadoc
1   /**
2    * Copyright 2005-2016 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.web.health;
17  
18  import com.codahale.metrics.Gauge;
19  import com.codahale.metrics.health.HealthCheck;
20  import org.kuali.rice.core.framework.persistence.platform.DatabasePlatform;
21  import org.springframework.jdbc.core.JdbcTemplate;
22  
23  import javax.sql.DataSource;
24  
25  /**
26   * A combination of health check and gauge which will check for successful connection to the given {@link DataSource}
27   * using the validation query defined on the given {@link DatabasePlatform}.
28   *
29   * @author Eric Westfall
30   */
31  public class DatabaseConnectionHealthGauge extends HealthCheck implements Gauge<Boolean> {
32  
33      private final DataSource dataSource;
34      private final DatabasePlatform platform;
35  
36      public DatabaseConnectionHealthGauge(DataSource dataSource, DatabasePlatform platform) {
37          this.dataSource = dataSource;
38          this.platform = platform;
39      }
40  
41      @Override
42      public Boolean getValue() {
43          Result result = execute();
44          return result.isHealthy();
45      }
46  
47      @Override
48      protected Result check() throws Exception {
49          JdbcTemplate template = new JdbcTemplate(dataSource);
50          template.execute(platform.getValidationQuery());
51          // if it's unhealthy, above method will throw an exception
52          return Result.healthy();
53      }
54  
55  }