aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorOfir Sonsino <ofir.sonsino@intl.att.com>2018-11-06 09:33:48 +0000
committerGerrit Code Review <gerrit@onap.org>2018-11-06 09:33:48 +0000
commit9daaecd1a2450fe2bae247ae320b4e7c6d7ceee5 (patch)
tree71f9de5d0d6240c0beb1f769671e30adf26f15f6
parent5a7cdb624c0abe6f2b7e80bcbbaa740c4ee35e39 (diff)
parent56f2ad282e7a8d316b92878ae151767fea847265 (diff)
Merge "HealthCheckController/test refactor"
-rw-r--r--docs/offeredapis.rst46
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java173
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java31
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java20
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java114
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java120
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java124
-rw-r--r--vid-app-common/src/test/resources/git.properties2
8 files changed, 297 insertions, 333 deletions
diff --git a/docs/offeredapis.rst b/docs/offeredapis.rst
index 4408bf6f0..4ee12612d 100644
--- a/docs/offeredapis.rst
+++ b/docs/offeredapis.rst
@@ -17,7 +17,7 @@ Offered APIs
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | - statusCode Either 200 or 500 |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | - The message contains additional detail in the case of an error, and is empty in the case of success. |
+| | | | - detailedMsg of the result, in case of failure particular error message |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -25,11 +25,11 @@ Offered APIs
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | { |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | “statusCode”:200, |
+| | | | “statusCode”: 200, |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | “message”:“health check succeeded”, |
+| | | | “detailedMsg”: “health check succeeded”, |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | “date”:null |
+| | | | “date”: current date |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | } |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -47,7 +47,7 @@ Offered APIs
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | - statusCode Either 200 or 500 |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | - message contains additional detail in the case of an error, and is empty in the case of success. |
+| | | | - detailedMsg of the result, in case of failure particular error message |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | - date string indicating the current date & time |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -57,9 +57,9 @@ Offered APIs
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | { |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | “statusCode”:200, |
+| | | | “statusCode”: 200, |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
-| | | | “message”:“health check succeeded”, |
+| | | | “detailedMsg”: “health check succeeded”, |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | “date”: current date |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
@@ -69,6 +69,38 @@ Offered APIs
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| Commit Version | GET | /commitInfo | Displays info about the last commit of the running build |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | return response entity: |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | - commitId full id of the commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | - commitMessageShort short message from the commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | - commitTime time of the commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | Expected: |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | { |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | “commitId”: id of the last commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | “commitMessageShort”: short message of the last commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | “commitTime”: time of the last commit |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | } |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
+| | | | |
++---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Change management | GET | change-management/workflow {vnfStringsList} | Get Workflow details for the VNFs list |
+---------------------+----------+-------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| | | | |
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
index 12cc68e61..86e832ba7 100644
--- a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
@@ -25,7 +25,7 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.dao.FnAppDoaImpl;
import org.onap.vid.model.GitRepositoryState;
-import org.springframework.beans.factory.annotation.Value;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -38,6 +38,9 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
+import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
+import static org.springframework.http.HttpStatus.OK;
+
/**
* Controller for user profile view. The view is restricted to authenticated
* users. The view name resolves to page user_profile.jsp which uses Angular.
@@ -47,158 +50,86 @@ import java.util.Properties;
@RequestMapping("/")
public class HealthCheckController extends UnRestrictedBaseController {
- /**
- * The logger.
- */
private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(HealthCheckController.class);
-
- /**
- * The Constant dateFormat.
- */
- final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
-
- private static final String HEALTH_CHECK_PATH = "/healthCheck";
+ private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
private static final String GIT_PROPERTIES_FILENAME = "git.properties";
+ private FnAppDoaImpl fnAppDoaImpl;
- /**
- * Model for JSON response with health-check results.
- */
- public class HealthStatus {
- // Either 200 or 500
- public int statusCode;
-
- // Additional detail in case of error, empty in case of success.
- public String message;
-
- public String date;
-
- public HealthStatus(int code, String msg) {
- this.statusCode = code;
- this.message = msg;
- }
-
- public HealthStatus(int code, String date, String msg) {
- this.statusCode = code;
- this.message = msg;
- this.date = date;
- }
-
- public int getStatusCode() {
- return statusCode;
- }
-
- public void setStatusCode(int code) {
- this.statusCode = code;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String msg) {
- this.message = msg;
- }
-
- public String getDate() {
- return date;
- }
-
- public void setDate(String date) {
- this.date = date;
- }
-
+ @Autowired
+ public HealthCheckController(FnAppDoaImpl fnAppDoaImpl) {
+ this.fnAppDoaImpl = fnAppDoaImpl;
}
- @SuppressWarnings("unchecked")
- public int getProfileCount(String driver, String URL, String username, String password) {
- FnAppDoaImpl doa = new FnAppDoaImpl();
- int count = doa.getProfileCount(driver, URL, username, password);
- return count;
- }
-
-
/**
* Obtain the HealthCheck Status from the System.Properties file.
* Used by IDNS for redundancy
*
* @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
*/
@RequestMapping(value = "/healthCheck", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public HealthStatus gethealthCheckStatusforIDNS() {
-
- String driver = SystemProperties.getProperty("db.driver");
- String URL = SystemProperties.getProperty("db.connectionURL");
- String username = SystemProperties.getProperty("db.userName");
- String password = SystemProperties.getProperty("db.password");
-
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::" + username);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "password::" + password);
-
-
- HealthStatus healthStatus = null;
- try {
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
- int count = getProfileCount(driver, URL, username, password);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::" + count);
- healthStatus = new HealthStatus(200, "health check succeeded");
- } catch (Exception ex) {
-
- LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- healthStatus = new HealthStatus(500, "health check failed: " + ex.toString());
- }
- return healthStatus;
+ public HealthStatus getHealthCheckStatusForIDNS() {
+ return createCorrespondingStatus();
}
/**
* Obtain the HealthCheck Status from the System.Properties file.
*
* @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * Project :
*/
@RequestMapping(value = "rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HealthStatus getHealthCheck(
@PathVariable("User-Agent") String UserAgent,
@PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) {
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent ", UserAgent);
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID ", ECOMPRequestID);
+ return createCorrespondingStatus();
+ }
- String driver = SystemProperties.getProperty("db.driver");
- String URL = SystemProperties.getProperty("db.connectionURL");
- String username = SystemProperties.getProperty("db.userName");
- String password = SystemProperties.getProperty("db.password");
-
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::" + username);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "password::" + password);
-
+ @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public GitRepositoryState getCommitInfo() throws IOException {
+ Properties properties = new Properties();
+ properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME));
+ return new GitRepositoryState(properties);
+ }
- HealthStatus healthStatus = null;
+ private HealthStatus createCorrespondingStatus() {
+ logData();
try {
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent" + UserAgent);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID" + ECOMPRequestID);
+ int count = fnAppDoaImpl.getProfileCount(getUrl(), getUsername(), getPassword());
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::", count);
+ return okStatus();
+ } catch (Exception ex) {
+ String errorMsg = ex.getMessage();
+ LOGGER.error(EELFLoggerDelegate.errorLogger, errorMsg);
+ return errorStatus(errorMsg);
+ }
+ }
+ private void logData() {
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::", getUrl());
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::", getUsername());
+ }
- int count = getProfileCount(driver, URL, username, password);
+ private HealthStatus okStatus() {
+ return new HealthStatus(OK, dateFormat.format(new Date()), "health check succeeded");
+ }
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::" + count);
- healthStatus = new HealthStatus(200, dateFormat.format(new Date()), "health check succeeded");
- } catch (Exception ex) {
+ private HealthStatus errorStatus(String msg) {
+ return new HealthStatus(INTERNAL_SERVER_ERROR, dateFormat.format(
+ new Date()), "health check failed: " + msg);
+ }
- LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- healthStatus = new HealthStatus(500, dateFormat.format(new Date()), "health check failed: " + ex.toString());
- }
- return healthStatus;
+ private String getUrl() {
+ return SystemProperties.getProperty("db.connectionURL");
}
- @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public GitRepositoryState getCommitInfo() throws IOException {
- Properties properties = new Properties();
- properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME));
- return new GitRepositoryState(properties);
+ private String getUsername() {
+ return SystemProperties.getProperty("db.userName");
+ }
+
+ private String getPassword() {
+ return SystemProperties.getProperty("db.password");
}
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java
new file mode 100644
index 000000000..6056c2898
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java
@@ -0,0 +1,31 @@
+package org.onap.vid.controllers;
+
+import org.springframework.http.HttpStatus;
+
+/**
+ * Model for JSON response with health-check results.
+ */
+public final class HealthStatus {
+
+ private final int statusCode;
+ private final String detailedMsg;
+ private final String date;
+
+ public HealthStatus(HttpStatus code, String date, String detailedMsg) {
+ this.statusCode = code.value();
+ this.detailedMsg = detailedMsg;
+ this.date = date;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getDetailedMsg() {
+ return detailedMsg;
+ }
+
+ public String getDate() {
+ return date;
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java b/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java
new file mode 100644
index 000000000..bd7a67b5a
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java
@@ -0,0 +1,20 @@
+package org.onap.vid.dao;
+
+import org.springframework.stereotype.Component;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+@Component
+public class ConnectionFactory {
+
+ public Connection getConnection(String url, String username, String password) throws SQLException {
+ checkNotNull(url);
+ checkNotNull(username);
+ checkNotNull(password);
+ return DriverManager.getConnection(url, username, password);
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
index 65fc5217f..e3fdc95f2 100644
--- a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
+++ b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
@@ -7,9 +7,9 @@
* 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.
@@ -21,94 +21,38 @@
package org.onap.vid.dao;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
import java.sql.*;
-
+@Repository
public class FnAppDoaImpl {
- /** The logger. */
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppDoaImpl.class);
-
- public int getProfileCount(String driver, String URL, String username, String password) {
- Connection dbc = null;
- PreparedStatement pst = null;
- ResultSet rs = null;
- String q = null;
- int count = 0;
- try {
- dbc = getConnection(URL,username,password);
- logger.debug(EELFLoggerDelegate.debugLogger, "getConnection:::"+ dbc);
- q = "select count(*) from fn_app";
- pst = dbc.prepareStatement(q);
- rs = pst.executeQuery();
-
- if (rs.next())
- count = rs.getInt(1);
- } catch(Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- } finally {
- cleanup(rs,pst,dbc);
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "count:::"+ count);
- return count;
- }
-
- public static Connection getConnection(String url, String username, String password) throws SQLException {
- java.sql.Connection con=null;
-
- if( url!=null && username!=null && password!=null ){
- con = DriverManager.getConnection(url, username, password);
- }
-
- logger.info("Connection Successful");
-
- return con;
-
- }
-
- public static void cleanup(ResultSet rs, PreparedStatement st, Connection c) {
- if (rs != null) {
- closeResultSet(rs);
- }
- if (st != null) {
- closePreparedStatement(st);
- }
- if (c != null) {
- rollbackAndCloseConnection(c);
- }
- }
-
- private static void rollbackAndCloseConnection(Connection c) {
- try {
- c.rollback();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to rollback connection", e);
+ static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppDoaImpl.class);
+
+ private ConnectionFactory connectionFactory;
+
+ @Autowired
+ public FnAppDoaImpl(ConnectionFactory connectionFactory) {
+ this.connectionFactory = connectionFactory;
+ }
+
+ public int getProfileCount(String URL, String username, String password) throws SQLException {
+ String q = "select count(*) from fn_app";
+ int count = 0;
+ try (Connection dbc = connectionFactory.getConnection(URL, username, password);
+ PreparedStatement pst = dbc.prepareStatement(q); ResultSet rs = pst.executeQuery()) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getConnection:::", dbc);
+ if (rs.next()) {
+ count = rs.getInt(1);
+ }
+ } catch (SQLException ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
+ throw ex;
}
- try {
- c.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close connection", e);
- }
- }
-
- private static void closePreparedStatement(PreparedStatement st) {
- try {
- st.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close statement", e);
- }
- }
- private static void closeResultSet(ResultSet rs) {
- try {
- rs.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close result set", e);
- }
- }
+ logger.debug(EELFLoggerDelegate.debugLogger, "count:::", count);
+ return count;
+ }
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java
index 6055bc390..da9cdaa6e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java
@@ -3,65 +3,99 @@ package org.onap.vid.controllers;
import org.apache.log4j.BasicConfigurator;
import org.junit.Before;
import org.junit.Test;
-import org.onap.vid.controllers.HealthCheckController.HealthStatus;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.vid.dao.FnAppDoaImpl;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import java.sql.SQLException;
+
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Matchers.anyString;
+import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
+import static org.springframework.http.HttpStatus.OK;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-
+@RunWith(MockitoJUnitRunner.class)
public class HealthCheckControllerTest {
- private HealthCheckController testSubject;
- private MockMvc mockMvc;
+ private static final String ERROR_MESSAGE = "error message";
+ private HealthCheckController testSubject;
+ private MockMvc mockMvc;
+
+ @Mock
+ private FnAppDoaImpl fnAppDoa;
- @Before
- public void setUp() {
- testSubject = new HealthCheckController();
- BasicConfigurator.configure();
- mockMvc = MockMvcBuilders.standaloneSetup(testSubject).build();
- }
+ @Before
+ public void setUp() {
+ testSubject = new HealthCheckController(fnAppDoa);
+ BasicConfigurator.configure();
+ mockMvc = MockMvcBuilders.standaloneSetup(testSubject).build();
+ }
- @Test
- public void testGetProfileCount() throws Exception {
- String driver = "";
- String URL = "";
- String username = "";
- String password = "";
- int result;
+ @Test
+ public void getHealthCheckStatusForIDNS_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception {
+ databaseConnectionEstablished();
+ mockMvc.perform(get("/healthCheck")
+ .accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.statusCode").value(OK.value()))
+ .andExpect(jsonPath("$.detailedMsg").value("health check succeeded"));
+ }
- // default test
- result = testSubject.getProfileCount(driver, URL, username, password);
- }
+ @Test
+ public void getHealthCheckStatusForIDNS_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception {
+ databaseNotAccessible();
+ mockMvc.perform(get("/healthCheck")
+ .accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value()))
+ .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE));
+ }
- @Test
- public void testGethealthCheckStatusforIDNS() throws Exception {
- HealthStatus result;
+ @Test
+ public void getHealthCheck_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception {
+ databaseConnectionEstablished();
+ mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId")
+ .accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.statusCode").value(OK.value()))
+ .andExpect(jsonPath("$.detailedMsg").value("health check succeeded"))
+ .andExpect(jsonPath("$.date").isString());
+ }
- // default test
- result = testSubject.gethealthCheckStatusforIDNS();
- }
+ @Test
+ public void getHealthCheck_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception {
+ databaseNotAccessible();
+ mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId")
+ .accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value()))
+ .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE));
+ }
- @Test
- public void testGetHealthCheck() throws Exception {
- String UserAgent = "";
- String ECOMPRequestID = "";
- HealthStatus result;
+ @Test
+ public void getCommitInfo_shouldReturnCommitData_whenCorrectPropertiesFileExists() throws Exception {
+ mockMvc.perform(get("/commitInfo")
+ .accept(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.commitId").value("123"))
+ .andExpect(jsonPath("$.commitMessageShort").value("Test short commit message"))
+ .andExpect(jsonPath("$.commitTime").value("1999-09-12T13:48:55+0200"));
+ }
- // default test
- result = testSubject.getHealthCheck(UserAgent, ECOMPRequestID);
- }
+ private void databaseConnectionEstablished() throws SQLException {
+ given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString()))
+ .willReturn(0);
+ }
- @Test
- public void testCommitInfoEndpoint() throws Exception {
- mockMvc.perform(get("/commitInfo")
- .accept(MediaType.APPLICATION_JSON))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.commitId").value("123987"))
- .andExpect(jsonPath("$.commitMessageShort").value("Test short commit message"))
- .andExpect(jsonPath("$.commitTime").value("1999-09-12T13:48:55+0200"));
- }
+ private void databaseNotAccessible() throws SQLException {
+ given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString()))
+ .willThrow(new SQLException(ERROR_MESSAGE));
+ }
} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java b/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java
index e7a7e3a37..2c2aa89a0 100644
--- a/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java
@@ -3,95 +3,67 @@ package org.onap.vid.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
+import java.sql.SQLException;
-import org.junit.Assert;
+import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.assertj.core.api.Java6Assertions.assertThatThrownBy;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Matchers.anyString;
+
+@RunWith(MockitoJUnitRunner.class)
public class FnAppDoaImplTest {
- private FnAppDoaImpl createTestSubject() {
- return new FnAppDoaImpl();
- }
+ private FnAppDoaImpl fnAppDoa;
- @Test
- public void testGetConnection() throws Exception {
- String driver2 = "";
- String url = "";
- String username = "";
- String password = "";
- Connection result;
-
- // test 1
- url = null;
- username = null;
- password = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
-
- // test 2
- url = "";
- username = null;
- password = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
-
- // test 3
- username = null;
- url = null;
- password = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
-
- // test 4
- username = "";
- url = null;
- password = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
-
- // test 5
- password = null;
- url = null;
- username = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
-
- // test 6
- password = "";
- url = null;
- username = null;
- result = FnAppDoaImpl.getConnection(driver2, url, username);
- Assert.assertEquals(null, result);
+ @Mock
+ private ConnectionFactory connectionFactory;
+
+ @Mock
+ private Connection connection;
+
+ @Mock
+ private PreparedStatement preparedStatement;
+
+ @Mock
+ private ResultSet resultSet;
+
+ private static final String ERROR_MESSAGE = "error message";
+ private static final String QUERY = "select count(*) from fn_app";
+
+ @Before
+ public void setUp() throws SQLException {
+ given(resultSet.next()).willReturn(true);
+ given(resultSet.getInt(1)).willReturn(5);
+ given(preparedStatement.executeQuery()).willReturn(resultSet);
+ given(connectionFactory.getConnection(anyString(), anyString(), anyString())).willReturn(connection);
+ fnAppDoa = new FnAppDoaImpl(connectionFactory);
}
- @Test
- public void testCleanup() throws Exception {
- ResultSet rs = null;
- PreparedStatement st = null;
+ private void okCaseSetUp() throws SQLException {
- // test 1
- rs = null;
- FnAppDoaImpl.cleanup(rs, st, null);
+ given(connection.prepareStatement(QUERY)).willReturn(preparedStatement);
+ }
- // test 2
- st = null;
- FnAppDoaImpl.cleanup(rs, st, null);
+ private void nokCaseSetup() throws SQLException {
+ given(connection.prepareStatement(QUERY)).willThrow(new SQLException(ERROR_MESSAGE));
+ }
- // test 3
- FnAppDoaImpl.cleanup(rs, st, null);
+ @Test
+ public void getProfileCount_shouldReturnNumber_whenNoExceptionIsThrown() throws SQLException {
+ okCaseSetUp();
+ assertThat(fnAppDoa.getProfileCount("anyUrl", "anyUsername", "anyPassword")).isEqualTo(5);
}
@Test
- public void testGetProfileCount() throws Exception {
- FnAppDoaImpl testSubject;
- String driver = "";
- String URL = "";
- String username = "";
- String password = "";
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getProfileCount(driver, URL, username, password);
+ public void getProfileCount_shouldRethrowSQLException() throws SQLException {
+ nokCaseSetup();
+ assertThatThrownBy(() -> fnAppDoa.getProfileCount("anyUrl", "anyUsername", "anyPassword"))
+ .isInstanceOf(SQLException.class).hasMessage(ERROR_MESSAGE);
}
} \ No newline at end of file
diff --git a/vid-app-common/src/test/resources/git.properties b/vid-app-common/src/test/resources/git.properties
index d504e3e88..6db5795a5 100644
--- a/vid-app-common/src/test/resources/git.properties
+++ b/vid-app-common/src/test/resources/git.properties
@@ -1,3 +1,3 @@
-git.commit.id=123987
+git.commit.id=123
git.commit.message.short=Test short commit message
git.commit.time=1999-09-12T13\:48\:55+0200 \ No newline at end of file