diff options
author | Dunietz, Irwin <id1681@att.com> | 2020-01-16 15:13:14 -0500 |
---|---|---|
committer | Takamune Cho <takamune.cho@att.com> | 2020-01-29 19:44:48 +0000 |
commit | b5fe8a69e90b950c07dc11af481eab7e9bab52c6 (patch) | |
tree | 3da81ce60554e65b93776b9aea647f3c6d8679ab /appc-dispatcher/appc-dispatcher-common/transaction-recorder/src | |
parent | 9b32cb60360a2a2973c621053510718de0072111 (diff) |
Change code in appc dispatcher for new LCMs in R6
Also introduce some minor improvements to robustness, efficiency, & formatting.
Issue-ID: APPC-1789
Signed-off-by: Dunietz, Irwin <id1681@att.com>
Change-Id: I82d970c2f7cde6c8dab1222af86ea70ce93b7e50
Diffstat (limited to 'appc-dispatcher/appc-dispatcher-common/transaction-recorder/src')
2 files changed, 238 insertions, 232 deletions
diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java index 15ed9ad4b..0acb2b5a0 100644 --- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java +++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/main/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImpl.java @@ -19,7 +19,6 @@ * 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. - * * ============LICENSE_END========================================================= */ @@ -37,17 +36,17 @@ import org.onap.ccsdk.sli.core.dblib.DbLibService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.sql.rowset.CachedRowSet; import java.sql.SQLException; +import javax.sql.rowset.CachedRowSet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.time.temporal.ChronoUnit; import static org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES.*; import static org.onap.appc.transactionrecorder.objects.TransactionConstants.*; @@ -74,44 +73,41 @@ public class TransactionRecorderImpl implements TransactionRecorder { */ @Override public void store(TransactionRecord record) throws APPCException { - if (logger.isTraceEnabled()) { - logger.trace("Transaction data insertion into DB"); - } - final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + - "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA + - ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA + - REQUEST_ID.getColumnName() + TransactionConstants.COMMA + - SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA + - ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA + - START_TIME.getColumnName() + TransactionConstants.COMMA + - END_TIME.getColumnName() + TransactionConstants.COMMA + - TARGET_ID.getColumnName() + TransactionConstants.COMMA + - TARGET_TYPE.getColumnName() + TransactionConstants.COMMA + - OPERATION.getColumnName() + TransactionConstants.COMMA + - RESULT_CODE.getColumnName() + TransactionConstants.COMMA + - DESCRIPTION.getColumnName() + TransactionConstants.COMMA + - STATE.getColumnName() + TransactionConstants.COMMA + - SERVICE_INSTANCE_ID + TransactionConstants.COMMA + - VNFC_NAME + TransactionConstants.COMMA + - VSERVER_ID + TransactionConstants.COMMA + - VF_MODULE_ID + TransactionConstants.COMMA + - MODE + ") " + - "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + logger.trace("Transaction data insertion into DB"); + final String STORE_DATE_QUERY = + TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + + "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA + + ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA + + REQUEST_ID.getColumnName() + TransactionConstants.COMMA + + SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA + + ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA + + START_TIME.getColumnName() + TransactionConstants.COMMA + + END_TIME.getColumnName() + TransactionConstants.COMMA + + TARGET_ID.getColumnName() + TransactionConstants.COMMA + + TARGET_TYPE.getColumnName() + TransactionConstants.COMMA + + OPERATION.getColumnName() + TransactionConstants.COMMA + + RESULT_CODE.getColumnName() + TransactionConstants.COMMA + + DESCRIPTION.getColumnName() + TransactionConstants.COMMA + + STATE.getColumnName() + TransactionConstants.COMMA + + SERVICE_INSTANCE_ID + TransactionConstants.COMMA + + VNFC_NAME + TransactionConstants.COMMA + + VSERVER_ID + TransactionConstants.COMMA + + VF_MODULE_ID + TransactionConstants.COMMA + + MODE + ") " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { dbLibService.writeData(STORE_DATE_QUERY, prepareArguments(record), SCHEMA); } catch (SQLException e) { logger.error("Error on storing record " + record.toString(), e); throw new APPCException(ERROR_ACCESSING_DATABASE, e); } - if (logger.isTraceEnabled()) { - logger.trace("Transaction Data Inserted Successfully into DB"); - } + logger.trace("Transaction Data Inserted Successfully into DB"); } @Override public void update(String key, - String requestId, - Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException { + String requestId, + Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException { logger.debug("Inside update in TransactionRecorderImpl"); if (appcInstanceId != null && checkIfNullInstanceEntryExist(key, requestId)) { @@ -151,15 +147,12 @@ public class TransactionRecorderImpl implements TransactionRecorder { logger.error("Error in updating records in updateTransactionEntry " + e); throw new APPCException(ERROR_ACCESSING_DATABASE, e); } - if (logger.isTraceEnabled()) { - logger.trace("Transaction data updated successfully"); - } - + logger.trace("Transaction data updated successfully"); } private void updateNullInstanceEntry(String key, - String requestId, - Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException { + String requestId, + Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException { logger.debug("Inside updateNullInstanceEntry"); ArrayList<String> values = new ArrayList<>(); @@ -180,7 +173,7 @@ public class TransactionRecorderImpl implements TransactionRecorder { if (logger.isDebugEnabled()) { logger.debug("Before updating Transaction table the Query is: " + query); for (String value : values) { - logger.debug("Value for Transaction table: " + value); + logger.debug("Value for Transaction table: " + value); } } Boolean result = dbLibService.writeData(query, values, SCHEMA); @@ -195,24 +188,24 @@ public class TransactionRecorderImpl implements TransactionRecorder { private boolean checkIfNullInstanceEntryExist(String key, String requestId) throws APPCException { logger.debug("Entered checkIfNullInstanceEntryExist"); - String nullInstanceCheckQuery = new String("SELECT COUNT(*) as ROWCOUNT FROM " + - TransactionConstants.TRANSACTIONS + WHERE + - TRANSACTION_ID.getColumnName() + " = ? AND " + - REQUEST_ID.getColumnName() + " = ? "); + String nullInstanceCheckQuery = new String( + "SELECT COUNT(*) as ROWCOUNT FROM " + + TransactionConstants.TRANSACTIONS + WHERE + + TRANSACTION_ID.getColumnName() + " = ? AND " + + REQUEST_ID.getColumnName() + " = ? "); ArrayList<String> nullInstanceCheckParams = new ArrayList<>(); nullInstanceCheckParams.add(null + "~" + key); nullInstanceCheckParams.add(requestId); - try{ - CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA); + try (CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA)) { int noRows = 0; if (rowSet != null && rowSet.first()) { noRows = rowSet.getInt("ROWCOUNT"); - logger.info("No of Rows in Transactions Table with TRANSACTION_ID: " + - null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows); + logger.info("No of Rows in Transactions Table with TRANSACTION_ID: " + + null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows); } - if(noRows > 0) + if (noRows > 0) return true; } catch (SQLException e) { logger.error("Error in checkIfNullInstanceEntryExist in the transaction table", e); @@ -223,14 +216,12 @@ public class TransactionRecorderImpl implements TransactionRecorder { @Override public void markTransactionsAborted(String appcInstanceId) { - if (logger.isTraceEnabled()) { - logger.trace("marking in progress transactions to aborted"); - } + logger.trace("marking in progress transactions to aborted"); final String updateQuery = - "UPDATE " + TransactionConstants.TRANSACTIONS + - " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "'," - + END_TIME.getColumnName() + " = ? " + - WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND " + "UPDATE " + TransactionConstants.TRANSACTIONS + + " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "'," + + END_TIME.getColumnName() + " = ? " + + WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND " + STATE.getColumnName() + " in (?,?)"; if (logger.isDebugEnabled()) { @@ -248,19 +239,18 @@ public class TransactionRecorderImpl implements TransactionRecorder { logger.error(message); throw new RuntimeException(message, e); } - if (logger.isTraceEnabled()) { - logger.trace("In progress transactions marked aborted"); - } + logger.trace("In progress transactions marked aborted"); } @Override public List<TransactionRecord> getInProgressRequests(TransactionRecord record, int interval) throws APPCException { - String IN_PROGRESS_REQUESTS_QUERY = "SELECT * FROM " + - TransactionConstants.TRANSACTIONS + WHERE + - TARGET_ID + " = ? AND " + - STATE.getColumnName() + " IN (?,?) AND " + - START_TIME.getColumnName() + " < ?"; + String IN_PROGRESS_REQUESTS_QUERY = + "SELECT * FROM " + + TransactionConstants.TRANSACTIONS + WHERE + + TARGET_ID + " = ? AND " + + STATE.getColumnName() + " IN (?,?) AND " + + START_TIME.getColumnName() + " < ?"; ArrayList<String> inProgressQueryParams = new ArrayList<>(); Instant window = record.getStartTime().minus(interval, ChronoUnit.HOURS); @@ -273,37 +263,40 @@ public class TransactionRecorderImpl implements TransactionRecorder { inProgressQueryParams.add(dateToStringConverterMillis(window)); } - try (CachedRowSet rowSet = dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) { + try (CachedRowSet rowSet = + dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) { List<TransactionRecord> inProgressRecords = new ArrayList<>(); TransactionRecord transaction; - while (rowSet.next()) { - transaction = new TransactionRecord(); - transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName())); - transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName())); - transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName())); - transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName())); - transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName()))); - transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName())); - transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName())); - transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName()))); - transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName()))); - transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName())); - transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName())); - transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName())); - transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName())); - transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName()))); - inProgressRecords.add(transaction); - } - if (logger.isTraceEnabled()) { - logger.trace("In progress transaction records fetched from database successfully."); + int count = 0; + if (rowSet != null) { + for (; rowSet.next(); ++count) { + transaction = new TransactionRecord(); + transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName())); + transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName())); + transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName())); + transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName())); + transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName()))); + transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName())); + transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName())); + transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName()))); + transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName()))); + transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName())); + transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName())); + transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName())); + transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName())); + transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName()))); + inProgressRecords.add(transaction); + } } + logger.trace(String.valueOf(count) + + " in progress transaction records fetched from database successfully."); return inProgressRecords; } catch (ParseException e) { logger.error("Error parsing start date during fetching in progress records ", e); throw new APPCException(ERROR_ACCESSING_DATABASE, e); } catch (SQLException e) { - logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~" + record - .getTransactionId(), e); + logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~" + + record.getTransactionId(), e); throw new APPCException(ERROR_ACCESSING_DATABASE, e); } } @@ -311,12 +304,12 @@ public class TransactionRecorderImpl implements TransactionRecorder { @Override public Boolean isTransactionDuplicate(TransactionRecord record) throws APPCException { - StringBuilder duplicateRequestCheckQuery = new StringBuilder("SELECT " + - TRANSACTION_ID.getColumnName() + " FROM " + - TransactionConstants.TRANSACTIONS + WHERE + - TRANSACTION_ID.getColumnName() + " <> ? AND " + - REQUEST_ID.getColumnName() + " = ? AND " + - STATE.getColumnName() + " IN(?,?) "); + StringBuilder duplicateRequestCheckQuery = new StringBuilder() + .append("SELECT ").append(TRANSACTION_ID.getColumnName()).append(" FROM ") + .append(TransactionConstants.TRANSACTIONS).append(WHERE) + .append(TRANSACTION_ID.getColumnName()).append(" <> ? AND ") + .append(REQUEST_ID.getColumnName()).append(" = ? AND ") + .append(STATE.getColumnName()).append(" IN(?,?) "); ArrayList<String> duplicateCheckParams = new ArrayList<>(); duplicateCheckParams.add(appcInstanceId + "~" + record.getTransactionId()); @@ -339,35 +332,37 @@ public class TransactionRecorderImpl implements TransactionRecorder { if (logger.isDebugEnabled()) { logger.debug(duplicateRequestCheckQuery.toString()); } - try (CachedRowSet rowSet = dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams, - SCHEMA)) { - if (rowSet.first()) { + try (CachedRowSet rowSet = + dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams, SCHEMA)) { + if (rowSet != null && rowSet.first()) { String transactionId = rowSet.getString(TRANSACTION_ID.getColumnName()); if (logger.isErrorEnabled()) { - logger.error("Duplicate request found. Transaction ID " + transactionId + " is currently in " + - "progress."); + logger.error("Duplicate request found. Transaction ID " + transactionId + + " is currently in progress."); } return true; } return false; } catch (SQLException e) { - logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~" + record - .getTransactionId(), e); + logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~" + + record.getTransactionId(), e); throw new APPCException(ERROR_ACCESSING_DATABASE, e); } } @Override public Integer getInProgressRequestsCount() throws APPCException { - final String inProgressRequestCountQuery = "SELECT COUNT(*) as VALUE FROM " - + TransactionConstants.TRANSACTIONS - + WHERE + STATE.getColumnName() + " IN (?,?) "; + final String inProgressRequestCountQuery = + "SELECT COUNT(*) as VALUE FROM " + + TransactionConstants.TRANSACTIONS + + WHERE + STATE.getColumnName() + " IN (?,?) "; ArrayList<String> checkInProgressParams = new ArrayList<>(); checkInProgressParams.add(RequestStatus.RECEIVED.name()); checkInProgressParams.add(RequestStatus.ACCEPTED.name()); - try(CachedRowSet rowSet=dbLibService.getData(inProgressRequestCountQuery,checkInProgressParams,SCHEMA)){ - if (rowSet.first()) { + try (CachedRowSet rowSet = + dbLibService.getData(inProgressRequestCountQuery, checkInProgressParams, SCHEMA)) { + if (rowSet != null && rowSet.first()) { int count = rowSet.getInt("VALUE"); logger.info("In progress request count fetched from database successfully."); return count; @@ -391,44 +386,51 @@ public class TransactionRecorderImpl implements TransactionRecorder { public List<RequestStatus> getRecords(String requestId, String subrequestId, String originatorId, String vnfId) throws APPCException { StringBuilder queryString = (new StringBuilder(1024)) - .append("SELECT " + TRANSACTION_ATTRIBUTES.STATE.getColumnName()) - .append(" FROM " + TRANSACTIONS) - .append(" WHERE " + TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName() + " = ? AND " + - TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName() + " = ?"); - + .append("SELECT ").append(TRANSACTION_ID.getColumnName()) + .append(",") + .append(STATE.getColumnName()) + .append(" FROM ").append(TRANSACTIONS) + .append(" WHERE ").append(TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName()).append(" = ? AND ") + .append(TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName()).append(" = ?"); ArrayList<String> argList = new ArrayList<>(); argList.add(requestId); argList.add(vnfId); if (subrequestId != null) { - queryString.append(" AND " + TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName() + " = ?"); + queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName()).append(" = ?"); argList.add(subrequestId); } if (originatorId != null) { - queryString.append(" AND " + TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName() + " = ?"); + queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName()).append(" = ?"); argList.add(originatorId); } List<RequestStatus> requestStatusList = new ArrayList<>(); - try { - CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA); - while (resultSet.next()) { - String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName()); - RequestStatus requestStatus = null; - try { - requestStatus = RequestStatus.valueOf(name); - } catch (IllegalArgumentException e) { - logger.error(String.format("Invalid request status (%s) using (%s) :", name, RequestStatus - .UNKNOWN), e); - requestStatus = RequestStatus.UNKNOWN; + try (CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA)) { + if (resultSet == null) { + logger.error(String.format( + "No results returned when retrieving record for requestID %s and vnfId %s %s", + requestId, vnfId, "from the transactions table")); + } else { + while (resultSet.next()) { + String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName()); + RequestStatus requestStatus = null; + try { + requestStatus = RequestStatus.valueOf(name); + } catch (IllegalArgumentException e) { + logger.error(String.format( + "Invalid request status (%s) using (%s):", name, RequestStatus.UNKNOWN), e); + requestStatus = RequestStatus.UNKNOWN; + } + requestStatusList.add(requestStatus); + logger.debug(String.format("Request Status obtained (%s).", requestStatus)); } - requestStatusList.add(requestStatus); - logger.debug(String.format("Request Status obtained (%s).", requestStatus)); } } catch (SQLException e) { logger.error("Error Accessing Database ", e); - throw new APPCException(String.format("Error retrieving record for requestID %s and vnfId %s " + - "from the transactions table", requestId, vnfId), e); + throw new APPCException(String.format( + "Error retrieving record for requestID %s and vnfId %s from the transactions table", + requestId, vnfId), e); } return requestStatusList; diff --git a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java index 36cf26bb7..394aa97a1 100644 --- a/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java +++ b/appc-dispatcher/appc-dispatcher-common/transaction-recorder/src/test/java/org/onap/appc/transactionrecorder/impl/TransactionRecorderImplTest.java @@ -19,31 +19,12 @@ * 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. - * * ============LICENSE_END========================================================= */ package org.onap.appc.transactionrecorder.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.hamcrest.CoreMatchers.isA; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.text.ParseException; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.sql.rowset.CachedRowSet; +import com.sun.rowset.CachedRowSetImpl; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -51,6 +32,11 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.hamcrest.CoreMatchers.isA; + import org.onap.appc.dao.util.dbcp.DBConnectionPool; import org.onap.appc.dao.util.helper.DBHelper; import org.onap.appc.domainmodel.lcm.Flags; @@ -61,7 +47,22 @@ import org.onap.appc.exceptions.APPCException; import org.onap.appc.transactionrecorder.objects.TransactionConstants; import org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES; import org.onap.ccsdk.sli.core.dblib.DbLibService; -import com.sun.rowset.CachedRowSetImpl; + +import javax.sql.rowset.CachedRowSet; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; /** * Test class for TransactionRecorder @@ -86,26 +87,27 @@ public class TransactionRecorderImplTest { * <p> * Please ensure this table create script is identical to the source script used in a deployment. */ - private String TRANSACTION_CREATE_TABLE = "CREATE TABLE TRANSACTIONS (" + - " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY," + - " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL," + - " REQUEST_ID VARCHAR(256) NOT NULL," + - " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL," + - " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL," + - " START_TIME DATETIME(3) NOT NULL," + - " END_TIME DATETIME(3) DEFAULT NULL," + - " TARGET_ID VARCHAR(256) NOT NULL," + - " TARGET_TYPE VARCHAR(256) DEFAULT NULL," + - " OPERATION VARCHAR(256) NOT NULL," + - " RESULT_CODE INT(11) DEFAULT NULL," + - " DESCRIPTION TEXT," + - " STATE VARCHAR(50) NOT NULL," + - " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL," + - " VNFC_NAME VARCHAR(256) DEFAULT NULL," + - " VSERVER_ID VARCHAR(256) DEFAULT NULL," + - " VF_MODULE_ID VARCHAR(256) DEFAULT NULL," + - " MODE VARCHAR(50) NOT NULL," + - ")"; + private String TRANSACTION_CREATE_TABLE = + "CREATE TABLE TRANSACTIONS (" + + " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY," + + " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL," + + " REQUEST_ID VARCHAR(256) NOT NULL," + + " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL," + + " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL," + + " START_TIME DATETIME(3) NOT NULL," + + " END_TIME DATETIME(3) DEFAULT NULL," + + " TARGET_ID VARCHAR(256) NOT NULL," + + " TARGET_TYPE VARCHAR(256) DEFAULT NULL," + + " OPERATION VARCHAR(256) NOT NULL," + + " RESULT_CODE INT(11) DEFAULT NULL," + + " DESCRIPTION TEXT," + + " STATE VARCHAR(50) NOT NULL," + + " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL," + + " VNFC_NAME VARCHAR(256) DEFAULT NULL," + + " VSERVER_ID VARCHAR(256) DEFAULT NULL," + + " VF_MODULE_ID VARCHAR(256) DEFAULT NULL," + + " MODE VARCHAR(50) NOT NULL," + + ")"; private String TRANSACTION_DROP_TABLE = "DROP TABLE IF EXISTS TRANSACTIONS"; @Rule @@ -151,8 +153,8 @@ public class TransactionRecorderImplTest { public void testStore() throws Exception { TransactionRecord input = prepareTransactionsInput(); - Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - testStoreInMemory(invocation.getArguments())); + Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> testStoreInMemory(invocation.getArguments())); transactionRecorderImpl.store(input); } @@ -175,8 +177,8 @@ public class TransactionRecorderImplTest { insertRecord(record1); TransactionRecord input = prepareTransactionsInput(); input.setStartTime(Instant.now()); - Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - inMemoryExecutionWithResultSet(invocation.getArguments())); + Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments())); Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 0).size()); } @@ -197,22 +199,22 @@ public class TransactionRecorderImplTest { @Test public void testGetInProgressRequestsWithinTimeInterval() throws SQLException, APPCException { TransactionRecord record1 = prepareTransactionsInput(); - record1.setStartTime(Instant.now().minus(4,ChronoUnit.HOURS)); + record1.setStartTime(Instant.now().minus(4, ChronoUnit.HOURS)); insertRecord(record1); TransactionRecord input = prepareTransactionsInput(); input.setStartTime(Instant.now()); - Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - inMemoryExecutionWithResultSet(invocation.getArguments())); - List<TransactionRecord> aList= transactionRecorderImpl.getInProgressRequests(input,12); - Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input,12).size()); + Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments())); + List<TransactionRecord> aList = transactionRecorderImpl.getInProgressRequests(input, 12); + Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 12).size()); } @Test public void testIsTransactionDuplicate() throws SQLException, APPCException { TransactionRecord input = prepareTransactionsInput(); - Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - inMemoryExecutionWithResultSet(invocation.getArguments())); + Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments())); Assert.assertFalse(transactionRecorderImpl.isTransactionDuplicate(input)); } @@ -274,10 +276,10 @@ public class TransactionRecorderImplTest { insertRecord(input); Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>(); updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall"); - Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - returnResult(invocation.getArguments())); - Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - testUpdateInMemory(invocation.getArguments())); + Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> returnResult(invocation.getArguments())); + Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments())); transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns); Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString()); Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString()); @@ -301,11 +303,10 @@ public class TransactionRecorderImplTest { TransactionRecord input = prepareTransactionsInput(); Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>(); updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall"); - Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - returnPositiveResult(invocation.getArguments())); - Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation -> - testUpdateInMemory(invocation.getArguments())); - + Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> returnPositiveResult(invocation.getArguments())); + Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())) + .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments())); transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns); Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString()); Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString()); @@ -319,9 +320,9 @@ public class TransactionRecorderImplTest { insertNullInstanceData(args.get(0)); try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps_second = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps_second = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { ps_second.setString(i, args.get(i - 1)); } @@ -332,12 +333,13 @@ public class TransactionRecorderImplTest { } private void insertNullInstanceData(String transactionId) throws Exception { - final String nullInstanceQuery = (TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + - " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + final String nullInstanceQuery = + TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(nullInstanceQuery) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(nullInstanceQuery) + ) { ArrayList<String> input = new ArrayList<String>(); input.add(transactionId); input.add(dateToStringConverterMillis(Instant.parse("2017-09-12T00:00:01.00Z"))); @@ -374,9 +376,9 @@ public class TransactionRecorderImplTest { ArrayList<String> args = (ArrayList<String>) obj[1]; System.out.println("Query: " + query + "\nArgs: " + args); try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { ps.setString(i, args.get(i - 1)); } @@ -430,9 +432,9 @@ public class TransactionRecorderImplTest { ArrayList<String> args = (ArrayList<String>) obj[1]; // System.out.println("Query: " + query + "\nArgs: " + args); try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { ps.setString(i, args.get(i - 1)); } @@ -446,9 +448,9 @@ public class TransactionRecorderImplTest { String query = (String) obj[0]; ArrayList<String> args = (ArrayList<String>) obj[1]; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { ps.setString(i, args.get(i - 1)); } @@ -460,13 +462,13 @@ public class TransactionRecorderImplTest { private boolean isTransactionAborted() throws Exception { String query = "SELECT COUNT(*) FROM TRANSACTIONS WHERE STATE = ?"; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { ps.setString(1, RequestStatus.ABORTED.toString()); try ( - ResultSet rs = ps.executeQuery() - ) { + ResultSet rs = ps.executeQuery() + ) { while (rs.next()) { int value = rs.getInt(1); if (value == 1) { @@ -483,9 +485,9 @@ public class TransactionRecorderImplTest { String query = (String) obj[0]; ArrayList<String> args = (ArrayList<String>) obj[1]; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { System.out.println("Value at " + i + ": " + args.get(i - 1)); ps.setString(i, args.get(i - 1)); @@ -504,9 +506,9 @@ public class TransactionRecorderImplTest { String query = (String) obj[0]; ArrayList<String> args = (ArrayList<String>) obj[1]; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(query) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(query) + ) { for (int i = 1; i <= args.size(); i++) { ps.setString(i, args.get(i - 1)); } @@ -538,12 +540,13 @@ public class TransactionRecorderImplTest { } private void insertRecord(TransactionRecord input) throws SQLException { - final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + - " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + final String STORE_DATE_QUERY = + TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS + + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY) - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY) + ) { ArrayList<String> args = prepareArguments(input); args.remove(0); args.add(0, "123~" + input.getTransactionId()); @@ -615,21 +618,22 @@ public class TransactionRecorderImplTest { private String checkIfValueIsUpdated(String key) throws Exception { try ( - Connection con = dbConnectionPool.getConnection(); - PreparedStatement ps = con.prepareStatement("SELECT TARGET_TYPE,TRANSACTION_ID FROM TRANSACTIONS" + - " WHERE TRANSACTION_ID = ?") - ) { + Connection con = dbConnectionPool.getConnection(); + PreparedStatement ps = con.prepareStatement( + "SELECT TARGET_TYPE, TRANSACTION_ID FROM TRANSACTIONS" + + " WHERE TRANSACTION_ID = ?") + ) { ps.setString(1, key); try ( - ResultSet rs = ps.executeQuery() - ) { - while (rs.next()) { - String value = rs.getString("TARGET_TYPE"); - String transactionId = rs.getString("TRANSACTION_ID"); - System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value); - return value; - } - throw new Exception("Value not found"); + ResultSet rs = ps.executeQuery() + ) { + while (rs.next()) { + String value = rs.getString("TARGET_TYPE"); + String transactionId = rs.getString("TRANSACTION_ID"); + System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value); + return value; + } + throw new Exception("Value not found"); } } } |