From 71340cf50ea2c0fc9cfd0670052c4b4fcabe3db6 Mon Sep 17 00:00:00 2001 From: Instrumental Date: Fri, 30 Nov 2018 14:21:02 -0600 Subject: Change Batch Packaging Issue-ID: AAF-654 Change-Id: Iaa1eab5d43717e7ffe51933511c9b232a5a1d770 Signed-off-by: Instrumental --- .../src/main/java/org/onap/aaf/auth/Batch.java | 513 --------------------- .../java/org/onap/aaf/auth/BatchException.java | 51 -- .../java/org/onap/aaf/auth/BatchPrincipal.java | 41 -- .../src/main/java/org/onap/aaf/auth/CassBatch.java | 82 ---- .../java/org/onap/aaf/auth/actions/Action.java | 29 -- .../java/org/onap/aaf/auth/actions/ActionDAO.java | 73 --- .../org/onap/aaf/auth/actions/ActionPuntDAO.java | 67 --- .../java/org/onap/aaf/auth/actions/CacheTouch.java | 53 --- .../java/org/onap/aaf/auth/actions/CredDelete.java | 55 --- .../java/org/onap/aaf/auth/actions/CredPrint.java | 56 --- .../java/org/onap/aaf/auth/actions/CredPunt.java | 70 --- .../main/java/org/onap/aaf/auth/actions/Email.java | 217 --------- .../java/org/onap/aaf/auth/actions/EmailPrint.java | 98 ---- .../org/onap/aaf/auth/actions/FuturePrint.java | 41 -- .../main/java/org/onap/aaf/auth/actions/Key.java | 26 -- .../java/org/onap/aaf/auth/actions/Message.java | 53 --- .../java/org/onap/aaf/auth/actions/NSACreate.java | 58 --- .../java/org/onap/aaf/auth/actions/NSADelete.java | 58 --- .../org/onap/aaf/auth/actions/NSDescUpdate.java | 58 --- .../java/org/onap/aaf/auth/actions/PermCreate.java | 69 --- .../java/org/onap/aaf/auth/actions/PermDelete.java | 64 --- .../java/org/onap/aaf/auth/actions/PermModify.java | 141 ------ .../java/org/onap/aaf/auth/actions/RoleCreate.java | 66 --- .../java/org/onap/aaf/auth/actions/RoleDelete.java | 62 --- .../java/org/onap/aaf/auth/actions/RoleModify.java | 152 ------ .../main/java/org/onap/aaf/auth/actions/URAdd.java | 57 --- .../java/org/onap/aaf/auth/actions/URDelete.java | 59 --- .../org/onap/aaf/auth/actions/URFutureApprove.java | 112 ----- .../onap/aaf/auth/actions/URFutureApproveExec.java | 108 ----- .../org/onap/aaf/auth/actions/URFuturePrint.java | 41 -- .../java/org/onap/aaf/auth/actions/URModify.java | 80 ---- .../java/org/onap/aaf/auth/actions/URPrint.java | 42 -- .../java/org/onap/aaf/auth/actions/URPunt.java | 70 --- .../main/java/org/onap/aaf/auth/batch/Batch.java | 513 +++++++++++++++++++++ .../org/onap/aaf/auth/batch/BatchException.java | 51 ++ .../org/onap/aaf/auth/batch/BatchPrincipal.java | 41 ++ .../java/org/onap/aaf/auth/batch/CassBatch.java | 82 ++++ .../org/onap/aaf/auth/batch/actions/Action.java | 29 ++ .../org/onap/aaf/auth/batch/actions/ActionDAO.java | 73 +++ .../onap/aaf/auth/batch/actions/ActionPuntDAO.java | 67 +++ .../onap/aaf/auth/batch/actions/CacheTouch.java | 53 +++ .../onap/aaf/auth/batch/actions/CredDelete.java | 55 +++ .../org/onap/aaf/auth/batch/actions/CredPrint.java | 56 +++ .../org/onap/aaf/auth/batch/actions/CredPunt.java | 70 +++ .../org/onap/aaf/auth/batch/actions/Email.java | 217 +++++++++ .../onap/aaf/auth/batch/actions/EmailPrint.java | 98 ++++ .../onap/aaf/auth/batch/actions/FuturePrint.java | 41 ++ .../java/org/onap/aaf/auth/batch/actions/Key.java | 26 ++ .../org/onap/aaf/auth/batch/actions/Message.java | 53 +++ .../org/onap/aaf/auth/batch/actions/NSACreate.java | 58 +++ .../org/onap/aaf/auth/batch/actions/NSADelete.java | 58 +++ .../onap/aaf/auth/batch/actions/NSDescUpdate.java | 58 +++ .../onap/aaf/auth/batch/actions/PermCreate.java | 69 +++ .../onap/aaf/auth/batch/actions/PermDelete.java | 64 +++ .../onap/aaf/auth/batch/actions/PermModify.java | 141 ++++++ .../onap/aaf/auth/batch/actions/RoleCreate.java | 66 +++ .../onap/aaf/auth/batch/actions/RoleDelete.java | 62 +++ .../onap/aaf/auth/batch/actions/RoleModify.java | 152 ++++++ .../org/onap/aaf/auth/batch/actions/URAdd.java | 57 +++ .../org/onap/aaf/auth/batch/actions/URDelete.java | 59 +++ .../aaf/auth/batch/actions/URFutureApprove.java | 112 +++++ .../auth/batch/actions/URFutureApproveExec.java | 108 +++++ .../onap/aaf/auth/batch/actions/URFuturePrint.java | 41 ++ .../org/onap/aaf/auth/batch/actions/URModify.java | 80 ++++ .../org/onap/aaf/auth/batch/actions/URPrint.java | 42 ++ .../org/onap/aaf/auth/batch/actions/URPunt.java | 70 +++ .../org/onap/aaf/auth/batch/helpers/Approval.java | 309 +++++++++++++ .../org/onap/aaf/auth/batch/helpers/Approver.java | 62 +++ .../org/onap/aaf/auth/batch/helpers/CQLBatch.java | 71 +++ .../onap/aaf/auth/batch/helpers/CacheChange.java | 63 +++ .../org/onap/aaf/auth/batch/helpers/Creator.java | 41 ++ .../java/org/onap/aaf/auth/batch/helpers/Cred.java | 325 +++++++++++++ .../onap/aaf/auth/batch/helpers/ExpireRange.java | 178 +++++++ .../org/onap/aaf/auth/batch/helpers/Future.java | 203 ++++++++ .../org/onap/aaf/auth/batch/helpers/History.java | 178 +++++++ .../onap/aaf/auth/batch/helpers/InputIterator.java | 73 +++ .../org/onap/aaf/auth/batch/helpers/Loader.java | 26 ++ .../org/onap/aaf/auth/batch/helpers/MiscID.java | 188 ++++++++ .../org/onap/aaf/auth/batch/helpers/MonthData.java | 120 +++++ .../java/org/onap/aaf/auth/batch/helpers/NS.java | 168 +++++++ .../onap/aaf/auth/batch/helpers/Notification.java | 209 +++++++++ .../org/onap/aaf/auth/batch/helpers/NsAttrib.java | 108 +++++ .../java/org/onap/aaf/auth/batch/helpers/Perm.java | 174 +++++++ .../java/org/onap/aaf/auth/batch/helpers/Role.java | 175 +++++++ .../org/onap/aaf/auth/batch/helpers/UserRole.java | 326 +++++++++++++ .../org/onap/aaf/auth/batch/helpers/Visitor.java | 25 + .../java/org/onap/aaf/auth/batch/helpers/X509.java | 119 +++++ .../org/onap/aaf/auth/batch/reports/Expiring.java | 301 ++++++++++++ .../onap/aaf/auth/batch/update/ExpiringOrig.java | 506 ++++++++++++++++++++ .../org/onap/aaf/auth/batch/update/ExpiringP2.java | 158 +++++++ .../aaf/auth/batch/update/NotifyApprovals.java | 236 ++++++++++ .../aaf/auth/batch/update/NotifyCredExpiring.java | 394 ++++++++++++++++ .../org/onap/aaf/auth/batch/update/Remove.java | 124 +++++ .../org/onap/aaf/auth/batch/update/Upload.java | 313 +++++++++++++ .../java/org/onap/aaf/auth/helpers/Approval.java | 309 ------------- .../java/org/onap/aaf/auth/helpers/Approver.java | 62 --- .../java/org/onap/aaf/auth/helpers/CQLBatch.java | 71 --- .../org/onap/aaf/auth/helpers/CacheChange.java | 63 --- .../java/org/onap/aaf/auth/helpers/Creator.java | 41 -- .../main/java/org/onap/aaf/auth/helpers/Cred.java | 325 ------------- .../java/org/onap/aaf/auth/helpers/Future.java | 203 -------- .../java/org/onap/aaf/auth/helpers/History.java | 178 ------- .../org/onap/aaf/auth/helpers/InputIterator.java | 73 --- .../java/org/onap/aaf/auth/helpers/Loader.java | 26 -- .../java/org/onap/aaf/auth/helpers/MiscID.java | 188 -------- .../java/org/onap/aaf/auth/helpers/MonthData.java | 120 ----- .../main/java/org/onap/aaf/auth/helpers/NS.java | 168 ------- .../org/onap/aaf/auth/helpers/Notification.java | 209 --------- .../java/org/onap/aaf/auth/helpers/NsAttrib.java | 108 ----- .../main/java/org/onap/aaf/auth/helpers/Perm.java | 174 ------- .../main/java/org/onap/aaf/auth/helpers/Role.java | 175 ------- .../java/org/onap/aaf/auth/helpers/UserRole.java | 322 ------------- .../java/org/onap/aaf/auth/helpers/Visitor.java | 25 - .../main/java/org/onap/aaf/auth/helpers/X509.java | 119 ----- .../java/org/onap/aaf/auth/reports/Expiring.java | 301 ------------ .../org/onap/aaf/auth/update/ExpiringOrig.java | 506 -------------------- .../java/org/onap/aaf/auth/update/ExpiringP2.java | 158 ------- .../org/onap/aaf/auth/update/NotifyApprovals.java | 236 ---------- .../onap/aaf/auth/update/NotifyCredExpiring.java | 394 ---------------- .../main/java/org/onap/aaf/auth/update/Remove.java | 124 ----- .../main/java/org/onap/aaf/auth/update/Upload.java | 313 ------------- .../onap/aaf/auth/actions/test/JU_ActionDAO.java | 95 ---- .../aaf/auth/actions/test/JU_CredPrintTest.java | 67 --- .../org/onap/aaf/auth/actions/test/JU_Email.java | 151 ------ .../onap/aaf/auth/actions/test/JU_EmailPrint.java | 92 ---- .../aaf/auth/actions/test/JU_FuturePrintTest.java | 61 --- .../org/onap/aaf/auth/actions/test/JU_Message.java | 62 --- .../auth/actions/test/JU_URFuturePrintTest.java | 57 --- .../onap/aaf/auth/actions/test/JU_URPrintTest.java | 58 --- .../aaf/auth/batch/actions/test/JU_ActionDAO.java | 95 ++++ .../auth/batch/actions/test/JU_CredPrintTest.java | 67 +++ .../onap/aaf/auth/batch/actions/test/JU_Email.java | 151 ++++++ .../aaf/auth/batch/actions/test/JU_EmailPrint.java | 92 ++++ .../batch/actions/test/JU_FuturePrintTest.java | 61 +++ .../aaf/auth/batch/actions/test/JU_Message.java | 62 +++ .../batch/actions/test/JU_URFuturePrintTest.java | 57 +++ .../auth/batch/actions/test/JU_URPrintTest.java | 58 +++ .../auth/batch/helpers/creators/RowCreator.java | 434 +++++++++++++++++ .../aaf/auth/batch/helpers/test/JU_Approval.java | 225 +++++++++ .../aaf/auth/batch/helpers/test/JU_Approver.java | 65 +++ .../auth/batch/helpers/test/JU_CacheChange.java | 80 ++++ .../aaf/auth/batch/helpers/test/JU_Creator.java | 72 +++ .../onap/aaf/auth/batch/helpers/test/JU_Cred.java | 142 ++++++ .../auth/batch/helpers/test/JU_ExpireRange.java | 71 +++ .../aaf/auth/batch/helpers/test/JU_Future.java | 177 +++++++ .../aaf/auth/batch/helpers/test/JU_History.java | 68 +++ .../auth/batch/helpers/test/JU_InputIterator.java | 76 +++ .../aaf/auth/batch/helpers/test/JU_MiscID.java | 97 ++++ .../aaf/auth/batch/helpers/test/JU_MonthData.java | 105 +++++ .../onap/aaf/auth/batch/helpers/test/JU_NS.java | 159 +++++++ .../aaf/auth/batch/helpers/test/JU_NsAttrib.java | 51 ++ .../onap/aaf/auth/batch/helpers/test/JU_Perm.java | 98 ++++ .../onap/aaf/auth/batch/helpers/test/JU_Role.java | 94 ++++ .../aaf/auth/batch/helpers/test/JU_UserRole.java | 186 ++++++++ .../org/onap/aaf/auth/batch/test/JU_Batch.java | 92 ++++ .../aaf/auth/batch/test/JU_BatchException.java | 59 +++ .../aaf/auth/batch/test/JU_BatchPrincipal.java | 48 ++ .../org/onap/aaf/auth/batch/test/JU_CassBatch.java | 67 +++ .../aaf/auth/batch/test/JU_NotificationTest.java | 80 ++++ .../onap/aaf/auth/helpers/JU_NotificationTest.java | 78 ---- .../onap/aaf/auth/helpers/creators/RowCreator.java | 434 ----------------- .../onap/aaf/auth/helpers/test/JU_Approval.java | 225 --------- .../onap/aaf/auth/helpers/test/JU_Approver.java | 65 --- .../onap/aaf/auth/helpers/test/JU_CacheChange.java | 80 ---- .../org/onap/aaf/auth/helpers/test/JU_Creator.java | 72 --- .../org/onap/aaf/auth/helpers/test/JU_Cred.java | 142 ------ .../org/onap/aaf/auth/helpers/test/JU_Future.java | 177 ------- .../org/onap/aaf/auth/helpers/test/JU_History.java | 68 --- .../aaf/auth/helpers/test/JU_InputIterator.java | 76 --- .../org/onap/aaf/auth/helpers/test/JU_MiscID.java | 97 ---- .../onap/aaf/auth/helpers/test/JU_MonthData.java | 105 ----- .../java/org/onap/aaf/auth/helpers/test/JU_NS.java | 159 ------- .../onap/aaf/auth/helpers/test/JU_NsAttrib.java | 51 -- .../org/onap/aaf/auth/helpers/test/JU_Perm.java | 98 ---- .../org/onap/aaf/auth/helpers/test/JU_Role.java | 94 ---- .../onap/aaf/auth/helpers/test/JU_UserRole.java | 186 -------- .../test/java/org/onap/aaf/auth/test/JU_Batch.java | 92 ---- .../org/onap/aaf/auth/test/JU_BatchException.java | 59 --- .../org/onap/aaf/auth/test/JU_BatchPrincipal.java | 48 -- .../java/org/onap/aaf/auth/test/JU_CassBatch.java | 67 --- .../java/org/onap/aaf/auth/org/ExpireRange.java | 178 ------- .../org/onap/aaf/auth/org/test/JU_ExpireRange.java | 71 --- 182 files changed, 11184 insertions(+), 11178 deletions(-) delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchException.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchPrincipal.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Action.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPrint.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/FuturePrint.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Key.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFuturePrint.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPrint.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchException.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchPrincipal.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/CassBatch.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Action.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionDAO.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionPuntDAO.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CacheTouch.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredDelete.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPrint.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPunt.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Email.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/EmailPrint.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/FuturePrint.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Key.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Message.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSACreate.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSADelete.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSDescUpdate.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermCreate.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermDelete.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermModify.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleCreate.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleDelete.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleModify.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URAdd.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URDelete.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApprove.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApproveExec.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFuturePrint.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URModify.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPrint.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPunt.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approver.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CacheChange.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/History.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/InputIterator.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Loader.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MiscID.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MonthData.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Notification.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NsAttrib.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Perm.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Expiring.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/ExpiringOrig.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/ExpiringP2.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyApprovals.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyCredExpiring.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java create mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approver.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CQLBatch.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Loader.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Visitor.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/X509.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/Expiring.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringOrig.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Remove.java delete mode 100644 auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Upload.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_ActionDAO.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_CredPrintTest.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Email.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_EmailPrint.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_FuturePrintTest.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Message.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URFuturePrintTest.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URPrintTest.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_ActionDAO.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_CredPrintTest.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Email.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_EmailPrint.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_FuturePrintTest.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Message.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URFuturePrintTest.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URPrintTest.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approver.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_CacheChange.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Creator.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Cred.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_History.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_InputIterator.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MiscID.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MonthData.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NsAttrib.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Perm.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Role.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_Batch.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchException.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchPrincipal.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_CassBatch.java create mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_NotificationTest.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/JU_NotificationTest.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/creators/RowCreator.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approval.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approver.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_CacheChange.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Creator.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Cred.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Future.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_History.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MiscID.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NS.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NsAttrib.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Perm.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Role.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_UserRole.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_Batch.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchException.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchPrincipal.java delete mode 100644 auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_CassBatch.java delete mode 100644 auth/auth-core/src/main/java/org/onap/aaf/auth/org/ExpireRange.java delete mode 100644 auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_ExpireRange.java diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java deleted file mode 100644 index 5a19ab38..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java +++ /dev/null @@ -1,513 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.lang.reflect.Constructor; -import java.net.InetAddress; -import java.net.URL; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.text.SimpleDateFormat; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.TimeZone; - -import org.onap.aaf.auth.common.Define; -import org.onap.aaf.auth.dao.CassAccess; -import org.onap.aaf.auth.dao.cass.RoleDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.hl.Question; -import org.onap.aaf.auth.env.AuthzEnv; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.Organization.Identity; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.auth.org.OrganizationFactory; -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.Access.Level; -import org.onap.aaf.cadi.config.Config; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.StaticSlot; -import org.onap.aaf.misc.env.TimeTaken; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.Statement; - -public abstract class Batch { - - private static String rootNs; - - private static StaticSlot ssargs; - - protected static final String STARS = "*****"; - - protected final Cluster cluster; - protected static AuthzEnv env; - protected static Session session; - protected static Set specialNames; - protected static boolean dryRun; - protected static String batchEnv; - - public static final String CASS_ENV = "CASS_ENV"; - public static final String LOG_DIR = "LOG_DIR"; - protected static final String PUNT="punt"; - protected static final String MAX_EMAILS="MAX_EMAILS"; - protected static final String VERSION="VERSION"; - public static final String GUI_URL="GUI_URL"; - - protected final Organization org; - - - - protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException { - // Be able to change Environments - // load extra properties, i.e. - // PERF.cassandra.clusters=.... - batchEnv = env.getProperty(CASS_ENV); - if (batchEnv != null) { - batchEnv = batchEnv.trim(); - env.info().log("Redirecting to ",batchEnv,"environment"); - String str; - for (String key : new String[]{ - CassAccess.CASSANDRA_CLUSTERS, - CassAccess.CASSANDRA_CLUSTERS_PORT, - CassAccess.CASSANDRA_CLUSTERS_USER_NAME, - CassAccess.CASSANDRA_CLUSTERS_PASSWORD, - VERSION,GUI_URL,PUNT,MAX_EMAILS, - LOG_DIR, - "SPECIAL_NAMES" - }) { - if ((str = env.getProperty(batchEnv+'.'+key))!=null) { - env.setProperty(key, str); - } - } - } - - // Setup for Dry Run - cluster = CassAccess.cluster(env,batchEnv); - env.info().log("cluster name - ",cluster.getClusterName()); - String dryRunStr = env.getProperty( "DRY_RUN" ); - if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) { - dryRun = false; - } else { - dryRun = true; - env.info().log("dryRun set to TRUE"); - } - - org = OrganizationFactory.init(env); - org.setTestMode(dryRun); - - // Special names to allow behaviors beyond normal rules - specialNames = new HashSet<>(); - String names = env.getProperty( "SPECIAL_NAMES" ); - if ( names != null ) - { - env.info().log("Loading SPECIAL_NAMES"); - for (String s :names.split(",") ) - { - env.info().log("\tspecial: " + s ); - specialNames.add( s.trim() ); - } - } - } - - protected abstract void run(AuthzTrans trans); - protected abstract void _close(AuthzTrans trans); - - public String[] args() { - return env.get(ssargs); - } - - public boolean isDryRun() - { - return dryRun; - } - - public boolean isSpecial(String user) { - if (specialNames != null && specialNames.contains(user)) { - env.info().log("specialName: " + user); - - return (true); - } else { - return (false); - } - } - - - protected PrintStream fallout(PrintStream inFallout, String logType) - throws IOException { - PrintStream fallout = inFallout; - if (fallout == null) { - File dir = new File("logs"); - if (!dir.exists()) { - dir.mkdirs(); - } - - File f = null; - long uniq = System.currentTimeMillis(); - - f = new File(dir, getClass().getSimpleName() + "_" + logType + "_" - + uniq + ".log"); - - fallout = new PrintStream(new FileOutputStream(f, true)); - } - return fallout; - } - - public Organization getOrgFromID(AuthzTrans trans, String user) { - Organization organization; - try { - organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase()); - } catch (OrganizationException e1) { - trans.error().log(e1); - organization=null; - } - - if (organization == null) { - PrintStream fallout = null; - - try { - fallout = fallout(fallout, "Fallout"); - fallout.print("INVALID_ID,"); - fallout.println(user); - } catch (Exception e) { - env.error().log("Could not write to Fallout File", e); - } - return (null); - } - - return (organization); - } - - public static Row executeDeleteQuery(Statement stmt) { - Row row = null; - if (!dryRun) { - row = session.execute(stmt).one(); - } - - return (row); - - } - - public static int acquireRunLock(String className) { - Boolean testEnv = true; - String envStr = env.getProperty("AFT_ENVIRONMENT"); - - if (envStr != null) { - if ("AFTPRD".equals(envStr)) { - testEnv = false; - } - } else { - env.fatal() - .log("AFT_ENVIRONMENT property is required and was not found. Exiting."); - System.exit(1); - } - - if (testEnv) { - env.info().log("TESTMODE: skipping RunLock"); - return (1); - } - - String hostname = null; - try { - hostname = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - e.printStackTrace(); - env.warn().log("Unable to get hostname"); - return (0); - } - - ResultSet existing = session.execute(String.format( - "select * from authz.run_lock where class = '%s'", className)); - - for (Row row : existing) { - long curr = System.currentTimeMillis(); - ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field - // by name? - - long interval = (1 * 60 * 1000); // @@ Create a value in props file - // for this - long prev = lastRun.getLong(); - - if ((curr - prev) <= interval) { - env.warn().log( - String.format("Too soon! Last run was %d minutes ago.", - ((curr - prev) / 1000) / 60)); - env.warn().log( - String.format("Min time between runs is %d minutes ", - (interval / 1000) / 60)); - env.warn().log( - String.format("Last ran on machine: %s at %s", - row.getString("host"), row.getDate("start"))); - return (0); - } else { - env.info().log("Delete old lock"); - deleteLock(className); - } - } - - GregorianCalendar current = new GregorianCalendar(); - - // We want our time in UTC, hence "+0000" - SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000"); - fmt.setTimeZone(TimeZone.getTimeZone("UTC")); - - String cql = String - .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS", - className, hostname, fmt.format(current.getTime())); - - env.info().log(cql); - - Row row = session.execute(cql).one(); - if (!row.getBool("[applied]")) { - env.warn().log("Lightweight Transaction failed to write lock."); - env.warn().log( - String.format("host with lock: %s, running at %s", - row.getString("host"), row.getDate("start"))); - return (0); - } - return (1); - } - - private static void deleteLock( String className) { - Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one(); - if (! row.getBool("[applied]")) { - env.info().log( "delete failed" ); - } - } - - private static void transferVMProps(AuthzEnv env, String ... props) { - String value; - for (String key : props) { - if ((value = System.getProperty(key))!=null) { - env.setProperty(key, value); - } - } - } - - // IMPORTANT! VALIDATE Organization isUser method - protected void checkOrganizationAcccess(AuthzTrans trans, Question q) throws APIException, OrganizationException { - Set testUsers = new HashSet<>(); - Result> rrd = q.roleDAO.readNS(trans, rootNs); - if (rrd.isOK()) { - for (RoleDAO.Data r : rrd.value) { - Result> rur = q.userRoleDAO.readByRole(trans, r.fullName()); - if (!rur.isOK()) { - continue; - } - for (UserRoleDAO.Data udd : rur.value) { - testUsers.add(udd.user); - } - } - if (testUsers.size() < 2) { - throw new APIException("Not enough Users in Roles for " + rootNs + " to Validate"); - } - - Identity iden; - for (String user : testUsers) { - if ((iden = org.getIdentity(trans, user)) == null) { - throw new APIException("Failed Organization Entity Validation Check: " + user); - } else { - trans.info().log("Organization Validation Check: " + iden.id()); - } - } - } - } - - protected static String logDir() { - String ld = env.getProperty(LOG_DIR); - if (ld==null) { - if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir - ld = "logs/"; - } else { - ld = "logs/"+batchEnv; - } - } - return ld; - } - protected int count(String str, char c) { - if (str==null || str.isEmpty()) { - return 0; - } else { - int count=1; - for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) { - ++count; - } - return count; - } - } - - public final void close(AuthzTrans trans) { - _close(trans); - cluster.close(); - } - - public static void main(String[] args) { - PropAccess access = new PropAccess(args); - InputStream is = null; - String filename; - String propLoc; - try { - Define.set(access); - rootNs =Define.ROOT_NS(); - if(access.getProperty(Config.CADI_PROP_FILES)==null) { - File f = new File("authBatch.props"); - try { - if (f.exists()) { - filename = f.getAbsolutePath(); - is = new FileInputStream(f); - propLoc = f.getPath(); - } else { - URL rsrc = ClassLoader.getSystemResource("authBatch.props"); - filename = rsrc.toString(); - is = rsrc.openStream(); - propLoc = rsrc.getPath(); - } - access.load(is); - } finally { - if (is == null) { - System.err.println("authBatch.props must exist in current dir, or in Classpath"); - System.exit(1); - } - is.close(); - } - if (filename != null) { - access.log(Level.INFO,"Instantiated properties from", filename); - } - - // Log where Config found - access.log(Level.INFO,"Configuring from", propLoc); - - } - env = new AuthzEnv(access); - - transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization"); - - // Flow all Env Logs to Log4j, with ENV - -// LogFileNamer lfn; -// lfn = new LogFileNamer(logDir(),"").noPID(); -// lfn.setAppender("authz-batch"); -// lfn.setAppender("aspr|ASPR"); -// lfn.setAppender("sync"); -// lfn.setAppender("jobchange"); -// lfn.setAppender("validateuser"); -// aspr = Logger.getLogger("aspr"); -// Log4JLogTarget.setLog4JEnv("authz-batch", env); -// propLoc = null; - - Batch batch = null; - // setup ATTUser and Organization Slots before starting this: - // TODO redo this - // env.slot(ATT.ATT_USERSLOT); - // - // OrganizationFactory.setDefaultOrg(env, ATT.class.getName()); - AuthzTrans trans = env.newTrans(); - - TimeTaken tt = trans.start("Total Run", Env.SUB); - try { - int len = args.length; - if (len > 0) { - String toolName = args[0]; - len -= 1; - if (len < 0) - len = 0; - String nargs[] = new String[len]; - if (len > 0) { - System.arraycopy(args, 1, nargs, 0, len); - } - - env.put(ssargs = env.staticSlot("ARGS"), nargs); - - /* - * Add New Batch Programs (inherit from Batch) here - */ - - // Might be a Report, Update or Temp Batch - Class cls; - String classifier = ""; - try { - cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.update." + toolName); - classifier = "Update:"; - } catch (ClassNotFoundException e) { - try { - cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.reports." + toolName); - classifier = "Report:"; - } catch (ClassNotFoundException e2) { - try { - cls = ClassLoader.getSystemClassLoader() - .loadClass("org.onap.aaf.auth.temp." + toolName); - classifier = "Temp Utility:"; - } catch (ClassNotFoundException e3) { - cls = null; - } - } - } - if (cls != null) { - Constructor cnst = cls.getConstructor(new Class[] { AuthzTrans.class }); - batch = (Batch) cnst.newInstance(trans); - env.info().log("Begin", classifier, toolName); - } - - - if (batch == null) { - trans.error().log("No Batch named", toolName, "found"); - } - /* - * End New Batch Programs (inherit from Batch) here - */ - - } - if (batch != null) { - batch.run(trans); - } - } finally { - tt.done(); - if (batch != null) { - batch.close(trans); - } - StringBuilder sb = new StringBuilder("Task Times\n"); - trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE); - trans.info().log(sb); - } - } catch (Exception e) { - e.printStackTrace(System.err); - // Exceptions thrown by DB aren't stopping the whole process. - System.exit(1); - } - } - -} - diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchException.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchException.java deleted file mode 100644 index 15bec4e4..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchException.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth; - -public class BatchException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -3877245367723491192L; - - public BatchException() { - } - - public BatchException(String message) { - super(message); - } - - public BatchException(Throwable cause) { - super(cause); - } - - public BatchException(String message, Throwable cause) { - super(message, cause); - } - - public BatchException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchPrincipal.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchPrincipal.java deleted file mode 100644 index 66431c8a..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/BatchPrincipal.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ -package org.onap.aaf.auth; - -import org.onap.aaf.cadi.principal.TaggedPrincipal; - -public class BatchPrincipal extends TaggedPrincipal { - private final String name; - - public BatchPrincipal(final String name) { - this.name = "batch:"+name; - } - - @Override - public String getName() { - return name; - } - - @Override - public String tag() { - return "Btch"; - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java deleted file mode 100644 index 4ebb3a94..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.impl.Log4JLogTarget; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.exceptions.InvalidQueryException; - -public abstract class CassBatch extends Batch { - - protected CassBatch(AuthzTrans trans, String log4JName) throws APIException, IOException, OrganizationException { - super(trans.env()); - // Flow all Env Logs to Log4j - Log4JLogTarget.setLog4JEnv(log4JName, env); - - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - } - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - trans.info().log("Closed Session"); - } - - public ResultSet executeQuery(String cql) { - return executeQuery(cql,""); - } - - public ResultSet executeQuery(String cql, String extra) { - if (isDryRun() && !cql.startsWith("SELECT")) { - if (extra!=null) { - env.info().log("Would query" + extra + ": " + cql); - } - } else { - if (extra!=null) { - env.info().log("query" + extra + ": " + cql); - } - try { - return session.execute(cql); - } catch (InvalidQueryException e) { - if (extra==null) { - env.info().log("query: " + cql); - } - throw e; - } - } - return null; - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Action.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Action.java deleted file mode 100644 index 54e2ee2d..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Action.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; - -public interface Action { - public Result exec(AuthzTrans trans, D data, T t); -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java deleted file mode 100644 index 5275cf93..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.CassAccess; -import org.onap.aaf.auth.dao.hl.Function; -import org.onap.aaf.auth.dao.hl.Question; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Session; - -public abstract class ActionDAO implements Action { - protected final Question q; - protected final Function f; - private boolean clean; - protected final boolean dryRun; - - public ActionDAO(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - q = new Question(trans, cluster, CassAccess.KEYSPACE, false); - f = new Function(trans,q); - clean = true; - this.dryRun = dryRun; - } - - public ActionDAO(AuthzTrans trans, ActionDAO predecessor) { - q = predecessor.q; - f = new Function(trans,q); - clean = false; - dryRun = predecessor.dryRun; - } - - public Session getSession(AuthzTrans trans) throws APIException, IOException { - return q.historyDAO.getSession(trans); - } - - public Question question() { - return q; - } - - public Function function() { - return f; - } - - public void close(AuthzTrans trans) { - if (clean) { - q.close(trans); - } - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java deleted file mode 100644 index ed032c95..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.Date; -import java.util.GregorianCalendar; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public abstract class ActionPuntDAO extends ActionDAO { - private int months; - protected static final Date now = new Date(); - - public ActionPuntDAO(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - this.months = months; - } - - public ActionPuntDAO(AuthzTrans trans, ActionDAO predecessor, int months, int range) { - super(trans, predecessor); - this.months = months; - } - - - protected Date puntDate(Date current) { - GregorianCalendar temp = new GregorianCalendar(); - temp.setTime(current); - temp.add(GregorianCalendar.MONTH, months); - - /* - * This method Randomized date. This is no longer needed. Just add the Punt Months. - temp.add(GregorianCalendar.MONTH, months); - if (range>0) { - int forward = Math.abs(random.nextInt()%range); - if (forward>1) { - temp.add(GregorianCalendar.MONTH, forward); - temp.add(GregorianCalendar.DAY_OF_MONTH, (random.nextInt()%30)-15); - } - } - */ - return temp.getTime(); - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java deleted file mode 100644 index 269edc77..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class CacheTouch extends ActionDAO { - - public CacheTouch(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public CacheTouch(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, String table, String text) { - if (dryRun) { - trans.info().printf("Would mark %s cache in DB for clearing: %s",table, text); - return Result.ok(); - } else { - Result rv = q.clearCache(trans, table); - trans.info().printf("Set DB Cache %s for clearing: %s",table, text); - return rv; - } - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java deleted file mode 100644 index ceb0453b..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class CredDelete extends ActionDAO { - - public CredDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public CredDelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, CredDAO.Data cred, String text) { - if (dryRun) { - trans.info().log("Would Delete:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); - return Result.ok(); - } else { - Result rv = q.credDAO.delete(trans, cred, true); // need to read for undelete - trans.info().log("Deleted:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); - return rv; - } - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPrint.java deleted file mode 100644 index 658ef8b5..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPrint.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.util.Chrono; - -public class CredPrint implements Action { - private String info; - - public CredPrint(String text) { - this.info = text; - } - - @Override - public Result exec(AuthzTrans trans, CredDAO.Data cred, String text) { - trans.info().log(info,cred.id,text, type(cred.type),Chrono.dateOnlyStamp(cred.expires)); - return Result.ok(); - } - - - public static String type(int type) { - switch(type) { - case CredDAO.BASIC_AUTH: // 1 - return "OLD"; - case CredDAO.BASIC_AUTH_SHA256: // 2 - return "U/P"; - case CredDAO.CERT_SHA256_RSA: // 200 - return "Cert"; - default: - return "Unknown"; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java deleted file mode 100644 index 33151d9f..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.Date; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class CredPunt extends ActionPuntDAO { - - public CredPunt(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws IOException, APIException { - super(trans,cluster,months,range,dryRun); - } - - public CredPunt(AuthzTrans trans, ActionDAO adao, int months, int range) throws IOException { - super(trans, adao, months,range); - } - - public Result exec(AuthzTrans trans, CredDAO.Data cdd,String text) { - Result rv = null; - Result> read = q.credDAO.read(trans, cdd); - if (read.isOKhasData()) { - for (CredDAO.Data data : read.value) { - Date from = data.expires; - data.expires = puntDate(from); - if (data.expires.compareTo(from)<=0) { - trans.debug().printf("Error: %s is before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); - } else { - if (dryRun) { - trans.info().log("Would Update Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); - } else { - trans.info().log("Updated Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); - rv = q.credDAO.update(trans, data); - } - } - } - } - if (rv==null) { - rv=Result.err(read); - } - return rv; - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java deleted file mode 100644 index f40eeb58..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java +++ /dev/null @@ -1,217 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.auth.org.Organization.Identity; -import org.onap.aaf.misc.env.util.Chrono; - -public class Email implements Action{ - protected final List toList; - protected final List ccList; - private final String[] defaultCC; - protected String subject; - private String preamble; - private Message msg; - private String sig; - protected String lineIndent=" "; - private long lastSent=0L; - - - public Email(String ... defaultCC) { - toList = new ArrayList<>(); - this.defaultCC = defaultCC; - ccList = new ArrayList<>(); - clear(); - } - - public Email clear() { - toList.clear(); - ccList.clear(); - for (String s: defaultCC) { - ccList.add(s); - } - return this; - } - - - public void indent(String indent) { - lineIndent = indent; - } - - public void preamble(String format, Object ... args) { - preamble = String.format(format, args); - } - - public Email addTo(Identity id) { - if (id!=null && !toList.contains(id.email())) { - toList.add(id.email()); - } - return this; - } - - public Email addTo(Collection users) { - for (String u : users) { - addTo(u); - } - return this; - } - - public Email addTo(String email) { - if (!toList.contains(email)) { - toList.add(email); - } - return this; - } - - public Email addCC(Identity id) { - if (id!=null && !ccList.contains(id.email())) { - ccList.add(id.email()); - } - return this; - } - - public Email addCC(String email) { - if (!ccList.contains(email)) { - ccList.add(email); - } - return this; - } - - - public Email add(Identity id, boolean toSuper) throws OrganizationException { - Identity responsible = id.responsibleTo(); - if (toSuper) { - addTo(responsible.email()); - addCC(id.email()); - } else { - addCC(responsible.email()); - addTo(id.email()); - } - return this; - } - - public Email subject(String format, Object ... args) { - if (format.contains("%s")) { - subject = String.format(format, args); - } else { - subject = format; - } - return this; - } - - - public Email signature(String format, Object ... args) { - sig = String.format(format, args); - return this; - } - - public void msg(Message msg) { - this.msg = msg; - } - - @Override - public Result exec(AuthzTrans trans, Organization org, String text) { - StringBuilder sb = new StringBuilder(); - if (preamble!=null) { - sb.append(lineIndent); - sb.append(preamble); - sb.append("\n\n"); - } - - if (msg!=null) { - msg.msg(sb,lineIndent); - sb.append("\n"); - } - - if (sig!=null) { - sb.append(sig); - sb.append("\n"); - } - - long ct = System.currentTimeMillis(); - long wait = ct-lastSent; - lastSent = ct; - if (wait < 100) { // 10 per second - try { - Thread.sleep(wait); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - return exec(trans,org,sb); - } - - protected Result exec(AuthzTrans trans, Organization org, StringBuilder sb) { - try { - /* int status = */ - org.sendEmail(trans, - toList, - ccList, - subject, - sb.toString(), - false); - } catch (Exception e) { - return Result.err(Result.ERR_ActionNotCompleted,e.getMessage()); - } - return Result.ok(); - - } - - public void log(PrintStream ps, String text) { - ps.print(Chrono.dateTime()); - boolean first = true; - for (String s : toList) { - if (first) { - first = false; - ps.print(": "); - } else { - ps.print(", "); - } - ps.print(s); - } - if (!ccList.isEmpty()) { - first=true; - for (String s : ccList) { - if (first) { - first = false; - ps.print(" ["); - } else { - ps.print(", "); - } - ps.print(s); - } - ps.print(']'); - } - - ps.print(' '); - ps.println(text); - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java deleted file mode 100644 index 141e382f..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.PrintStream; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.auth.org.Organization; - -public class EmailPrint extends Email { - - private static final int LINE_LENGTH = 100; - - public EmailPrint(String... defaultCC) { - super(defaultCC); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.actions.Email#exec(org.onap.aaf.auth.org.test.Organization, java.lang.StringBuilder) - */ - @Override - protected Result exec(AuthzTrans trans, Organization org, StringBuilder msg) { - PrintStream out = System.out; - boolean first = true; - out.print("To: "); - for (String s: toList) { - if (first) {first = false;} - else {out.print(',');} - out.print(s); - } - out.println(); - - first = true; - out.print("CC: "); - for (String s: ccList) { - if (first) {first = false;} - else {out.print(',');} - out.print(s); - } - out.println(); - - out.print("Subject: "); - out.println(subject); - out.println(); - boolean go = true; - - for (int start=0, end=LINE_LENGTH;go;start=end,end=Math.min(msg.length(), start+LINE_LENGTH)) { - int ret = msg.indexOf("\n",start+1); - switch(ret) { - case -1: - out.println(msg.substring(start,end)); - break; - case 0: - end=start+1; - out.println(); - break; - default: - if (retstart && ret { - private String info; - - public FuturePrint(String text) { - this.info = text; - } - - @Override - public Result exec(AuthzTrans trans, Future f, String text) { - trans.info().log(info,f.id(),f.memo(),"expiring on",Chrono.dateOnlyStamp(f.expires())); - return Result.ok(); - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Key.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Key.java deleted file mode 100644 index ee2e8c3b..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Key.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -public interface Key { - public String key(HELPER H); -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java deleted file mode 100644 index f1eadb20..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.util.ArrayList; -import java.util.List; - -public class Message { - public final List lines; - - public Message() { - lines = new ArrayList<>(); - } - - public void clear() { - lines.clear(); - } - - public String line(String format, Object ... args) { - String rv=String.format(format, args); - lines.add(rv); - return rv; - } - - public void msg(StringBuilder sb, String lineIndent) { - if (!lines.isEmpty()) { - for (String line : lines) { - sb.append(lineIndent); - sb.append(line); - sb.append('\n'); - } - } - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java deleted file mode 100644 index 58a8c4b8..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.NsAttrib; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class NSACreate extends ActionDAO { - public NSACreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public NSACreate(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { - if (dryRun) { - trans.info().printf("Would Create %s Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); - return Result.ok(); - } else { - Result rv = q.nsDAO.dao().attribAdd(trans, nsa.ns, nsa.key, nsa.value); - if (rv.isOK()) { - trans.info().printf("%s - Created Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); - } else { - trans.error().printf("Error Creating Attrib '%s=%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java deleted file mode 100644 index c8a1c82c..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.NsAttrib; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class NSADelete extends ActionDAO { - public NSADelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public NSADelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { - if (dryRun) { - trans.info().printf("Would Delete %s Attrib '%s' in %s",text,nsa.key,nsa.ns); - return Result.ok(); - } else { - Result rv = q.nsDAO.dao().attribRemove(trans, nsa.ns, nsa.key); - if (rv.isOK()) { - trans.info().printf("%s - Deleted Attrib '%s' in %s",text,nsa.key,nsa.value,nsa.ns); - } else { - trans.error().printf("Error Deleting Attrib '%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java deleted file mode 100644 index d5d93b38..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.NS; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class NSDescUpdate extends ActionDAO { - public NSDescUpdate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public NSDescUpdate(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, NS ns, String desc) { - if (dryRun) { - trans.info().printf("Would Update '%s' Description to '%s'",ns,desc); - return Result.ok(); - } else { - Result rv = q.nsDAO.dao().addDescription(trans, ns.name, desc); - if (rv.isOK()) { - trans.info().printf("Updated '%s' Description to '%s'",ns,desc); - } else { - trans.error().printf("Error Updating '%s' Description to '%s' - %s",ns,desc,rv.details); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java deleted file mode 100644 index a6c02f2c..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.PermDAO; -import org.onap.aaf.auth.dao.cass.PermDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Perm; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - - -public class PermCreate extends ActionDAO { - public PermCreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public PermCreate(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, Perm p,String text) { - PermDAO.Data pdd = new PermDAO.Data(); - pdd.ns = p.ns; - pdd.type = p.type; - pdd.instance = p.instance; - pdd.action = p.action; - pdd.description = p.description; - pdd.roles = p.roles; - - if (dryRun) { - trans.info().log("Would Create Perm:",text,p.fullType()); - return Result.ok(pdd); - } else { - Result rv = q.permDAO.create(trans, pdd); // need to read for undelete - if (rv.isOK()) { - trans.info().log("Created Perm:",text,p.fullType()); - } else { - trans.error().log("Error Creating Role -",rv.details,":",p.fullType()); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java deleted file mode 100644 index db549948..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.PermDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Perm; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class PermDelete extends ActionDAO { - public PermDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public PermDelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, Perm p,String text) { - PermDAO.Data pdd = new PermDAO.Data(); - pdd.ns = p.ns; - pdd.type = p.type; - pdd.instance = p.instance; - pdd.action = p.action; - if (dryRun) { - trans.info().log("Would Delete Perm:",text,p.fullType()); - return Result.ok(); - } else { - Result rv = q.permDAO.delete(trans, pdd, true); // need to read for undelete - if (rv.isOK()) { - trans.info().log("Deleted Perm:",text,p.fullType()); - } else { - trans.error().log("Error Deleting Perm -",rv.details,":",p.fullType()); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java deleted file mode 100644 index a3d4bb6d..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.PermDAO; -import org.onap.aaf.auth.dao.cass.RoleDAO; -import org.onap.aaf.auth.dao.cass.Status; -import org.onap.aaf.auth.dao.cass.PermDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Perm; -import org.onap.aaf.auth.helpers.Role; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class PermModify extends ActionDAO { - public PermModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public PermModify(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, final Perm p, final Modify modify) { - Result> rr = q.permDAO.read(trans, p.ns,p.type,p.instance,p.action); - if (dryRun) { - if (rr.isOKhasData()) { - return Result.ok(rr.value.get(0)); - } else { - return Result.err(Result.ERR_NotFound, "Data not Found " + p.toString()); - } - } else { - Result rv = null; - if (rr.isOKhasData()) { - for (final Data d : rr.value) { - modify.change(d); - if (d.ns.equals(p.ns) && d.type.equals(p.type) && d.instance.equals(p.instance) && d.action.equals(p.action)) { - // update for fields - // In either case, adjust Permissions - for (String r : d.roles) { - if (!p.roles.contains(r)) { - q.permDAO.dao().addRole(trans, d, r); - } - } - for (String r : p.roles) { - if (!d.roles.contains(r)) { - q.permDAO.dao().delRole(trans, d, r); - } - } - rv = Result.ok(d); - } else { - for (String r : d.roles) { - Role role = Role.keys.get(r); - if (role.perms.contains(p.encode())) { - modify.roleModify().exec(trans, role, new RoleModify.Modify() { - @Override - public PermModify permModify() { - return PermModify.this; - } - - @Override - public void change(RoleDAO.Data rdd) { - rdd.perms.remove(p.encode()); - rdd.perms.add(d.encode()); - } - }); - } - } - - rv = q.permDAO.create(trans, d); - if (rv.isOK()) { - PermDAO.Data pdd = new PermDAO.Data(); - pdd.ns = p.ns; - pdd.type = p.type; - pdd.instance = p.instance; - pdd.action = p.action; - q.permDAO.delete(trans, pdd, false); - trans.info().printf("Updated %s|%s|%s|%s to %s|%s|%s|%s\n", - p.ns, p.type, p.instance, p.action, - d.ns, d.type, d.instance, d.action); - } else { - trans.info().log(rv.errorString()); - } - } - - } - } else { - rv = Result.err(rr); - } - if (rv==null) { - rv = Result.err(Status.ERR_General,"Never get to this code"); - } - - return rv; - } - } - - public static interface Modify { - void change(PermDAO.Data ur); - RoleModify roleModify(); - } - - public Result delete(AuthzTrans trans, Perm p) { - if (dryRun) { - return Result.ok(); - } else { - PermDAO.Data data = new PermDAO.Data(); - data.ns=p.ns; - data.type = p.type; - data.instance = p.instance; - data.action = p.action; - return q.permDAO.delete(trans,data,false); - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java deleted file mode 100644 index cdbe92b4..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.RoleDAO; -import org.onap.aaf.auth.dao.cass.RoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Role; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class RoleCreate extends ActionDAO { - public RoleCreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public RoleCreate(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, Role r,String text) { - RoleDAO.Data rdd = new RoleDAO.Data(); - rdd.ns = r.ns; - rdd.name = r.name; - rdd.description = r.description; - rdd.perms = r.perms; - - if (dryRun) { - trans.info().log("Would Create Role:",text,r.fullName()); - return Result.ok(rdd); - } else { - Result rv = q.roleDAO.create(trans, rdd); // need to read for undelete - if (rv.isOK()) { - trans.info().log("Created Role:",text,r.fullName()); - } else { - trans.error().log("Error Creating Role -",rv.details,":",r.fullName()); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java deleted file mode 100644 index 67491b5b..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.RoleDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Role; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class RoleDelete extends ActionDAO { - public RoleDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public RoleDelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, Role r,String text) { - if (dryRun) { - trans.info().log("Would Delete Role:",text,r.fullName()); - return Result.ok(); - } else { - RoleDAO.Data rdd = new RoleDAO.Data(); - rdd.ns = r.ns; - rdd.name = r.name; - Result rv = q.roleDAO.delete(trans, rdd, true); // need to read for undelete - if (rv.isOK()) { - trans.info().log("Deleted Role:",text,r.fullName()); - } else { - trans.error().log("Error Deleting Role -",rv.details,":",r.fullName()); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java deleted file mode 100644 index 75937ef7..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.PermDAO; -import org.onap.aaf.auth.dao.cass.RoleDAO; -import org.onap.aaf.auth.dao.cass.Status; -import org.onap.aaf.auth.dao.cass.RoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Perm; -import org.onap.aaf.auth.helpers.Role; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class RoleModify extends ActionDAO { - public RoleModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - } - - public RoleModify(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(final AuthzTrans trans, final Role r,final RoleModify.Modify modify) { - Result> rr = q.roleDAO.read(trans, r.ns,r.name); - if (dryRun) { - if (rr.isOKhasData()) { - return Result.ok(rr.value.get(0)); - } else { - return Result.err(Result.ERR_NotFound, "Data not Found " + r.toString()); - } - } else { - Result rv = null; - if (rr.isOKhasData()) { - for (final Data d : rr.value) { - modify.change(d); - if (d.ns.equals(r.ns) && d.name.equals(r.name)) { - // update for fields - // In either case, adjust Roles - for (String p : d.perms) { - if (!r.perms.contains(p)) { - Result rpdd = PermDAO.Data.decode(trans, q, p); - if (rpdd.isOKhasData()) { - q.roleDAO.dao().addPerm(trans, d, rpdd.value); - } - } - } - for (String p : r.perms) { - if (!d.perms.contains(p)) { - Result rpdd = PermDAO.Data.decode(trans, q, p); - if (rpdd.isOKhasData()) { - q.roleDAO.dao().delPerm(trans, d, rpdd.value); - } - } - } - rv = Result.ok(d); - } else { - for (String p : d.perms) { - Perm perm = Perm.keys.get(p); - if (perm!=null) { - if (perm.roles.contains(r.encode())) { - modify.permModify().exec(trans, perm, new PermModify.Modify() { - @Override - public RoleModify roleModify() { - return RoleModify.this; - } - - @Override - public void change(PermDAO.Data pdd) { - pdd.roles.remove(r.encode()); - pdd.roles.add(d.encode()); - } - }); - } - } - } - Result> preexist = q.roleDAO.read(trans, d); - if (preexist.isOKhasData()) { - Data rdd = preexist.value.get(0); - for (String p : d.perms) { - Result perm = PermDAO.Data.decode(trans, q, p); - if (perm.isOKhasData()) { - q.roleDAO.dao().addPerm(trans,rdd, perm.value); - } - } - rv = Result.ok(rdd); - } else { - rv = q.roleDAO.create(trans, d); - } - if (rv.isOK()) { - trans.info().printf("Updating %s|%s to %s|%s", r.ns, r.name, d.ns, d.name); - RoleDAO.Data rmme = new RoleDAO.Data(); - rmme.ns=r.ns; - rmme.name=r.name; - q.roleDAO.delete(trans, rmme, false); - - } else { - trans.info().log(rv.errorString()); - } - } - } - } else { - rv = Result.err(rr); - } - if (rv==null) { - rv = Result.err(Status.ERR_General,"Never get to this code"); - } - return rv; - } - } - - public static interface Modify { - void change(RoleDAO.Data ur); - PermModify permModify(); - } - - public Result delete(AuthzTrans trans, Role r) { - if (dryRun) { - return Result.ok(); - } else { - RoleDAO.Data data = new RoleDAO.Data(); - data.ns=r.ns; - data.name = r.name; - return q.roleDAO.delete(trans,data,false); - } - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java deleted file mode 100644 index 4538c56b..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class URAdd extends ActionDAO { - public URAdd(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public URAdd(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur, String text) { - if (dryRun) { - trans.info().log("Would Add:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); - return Result.ok(ur.urdd()); - } else { - Result rv = q.userRoleDAO.create(trans, ur.urdd()); - trans.info().log("Added:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java deleted file mode 100644 index cf519f6f..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class URDelete extends ActionDAO { - public URDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public URDelete(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur,String text) { - if (dryRun) { - trans.info().log("Would Delete UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); - return Result.ok(); - } else { - Result rv = q.userRoleDAO.delete(trans,ur.urdd(), true); // need to read for undelete - if (rv.isOK()) { - trans.info().log("Deleted UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); - } else { - trans.error().log("Error Deleting User Role -",rv.details,":",ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires()) ); - } - return rv; - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java deleted file mode 100644 index 63d4ef7c..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.Date; -import java.util.GregorianCalendar; - -import org.onap.aaf.auth.dao.cass.FutureDAO; -import org.onap.aaf.auth.dao.cass.NsDAO; -import org.onap.aaf.auth.dao.hl.Function; -import org.onap.aaf.auth.dao.hl.Question; -import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Approval; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.auth.org.Organization.Expiration; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class URFutureApprove extends ActionDAO implements Action, Key { - private final Date start; - private final Date expires; - - public URFutureApprove(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans,cluster, dryRun); - GregorianCalendar gc = new GregorianCalendar(); - start = gc.getTime(); - expires = trans.org().expiration(gc, Expiration.Future).getTime(); - } - - public URFutureApprove(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - GregorianCalendar gc = new GregorianCalendar(); - start = gc.getTime(); - expires = trans.org().expiration(gc, Expiration.Future).getTime(); - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur,String text) { - if (dryRun) { - return Result.ok(text); - } else { - Result rns = q.deriveNs(trans, ur.ns()); - if (rns.isOK()) { - - FutureDAO.Data data = new FutureDAO.Data(); - data.id=null; // let Create function assign UUID - data.target=Function.FOP_USER_ROLE; - - data.memo = key(ur); - data.start = start; - data.expires = ur.expires(); - try { - data.construct = ur.urdd().bytify(); - } catch (IOException e) { - return Result.err(e); - } - Result rfuture = f.createFuture(trans, data, Function.FOP_USER_ROLE, ur.user(), rns.value, FUTURE_OP.A); - if (rfuture.isOK()) { - trans.info().log(rfuture.value, text, ur.user(), data.memo); - } else { - trans.error().log(rfuture.details, text); - } - return rfuture; - } else { - return Result.err(rns); - } - } - } - - @Override - public String key(UserRole ur) { - String expire; - if (expires.before(start)) { - expire = "' - EXPIRED "; - } else { - expire = "' - expiring "; - } - - if (Question.OWNER.equals(ur.rname())) { - return Approval.RE_VALIDATE_OWNER + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); - } else if (Question.ADMIN.equals(ur.rname())) { - return Approval.RE_VALIDATE_ADMIN + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); - } else { - return Approval.RE_APPROVAL_IN_ROLE + ur.role() + expire + Chrono.dateOnlyStamp(ur.expires()); - } - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java deleted file mode 100644 index 75bbd813..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.ApprovalDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.cass.ApprovalDAO.Data; -import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP; -import org.onap.aaf.auth.dao.hl.Function.Lookup; -import org.onap.aaf.auth.dao.hl.Function.OP_STATUS; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Approval; -import org.onap.aaf.auth.helpers.Future; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class URFutureApproveExec extends ActionDAO, OP_STATUS, Future> { - - public URFutureApproveExec(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans,cluster, dryRun); - } - - public URFutureApproveExec(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, List app, Future future) { - if (dryRun) { - return Result.err(Result.ERR_ActionNotCompleted,"Not Executed"); - } else { - // Save on Lookups - final List apprs = new ArrayList<>(); - final List urs = new ArrayList<>(); - for (Approval a : app) { - apprs.add(a.add); - UserRole ur = UserRole.get(a.add.user, future.role); - if (ur!=null) { - urs.add(ur.urdd()); - } - } - Result rv = f.performFutureOp(trans, FUTURE_OP.A, future.fdd, - new Lookup>() { - @Override - public List get(AuthzTrans trans, Object ... noop) { - return apprs; - } - }, - new Lookup() { - @Override - public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { - List lur = UserRole.getByUser().get(keys[0]); - if (lur!=null) { - for (UserRole ur : lur) { - if (ur.role().equals(keys[1])) { - return ur.urdd(); - } - } - } - return null; - } - }); - if (rv.isOK()) { - switch(rv.value) { - case D: - trans.info().printf("Denied %s on %s", future.memo(),future.fdd.target); - break; - case E: - trans.info().printf("Completed %s on %s", future.memo(),future.fdd.target); - break; - case L: - trans.info().printf("Future %s on %s has lapsed", future.memo(),future.fdd.target); - break; - default: - } - } else { - trans.error().log("Error completing",future.memo(),rv.errorString()); - } - return rv; - } - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFuturePrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFuturePrint.java deleted file mode 100644 index b749c648..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFuturePrint.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.util.Chrono; - - -public class URFuturePrint implements Action { - private String info; - - public URFuturePrint(String text) { - this.info = text; - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur, String text) { - trans.info().log(info,text,ur.user(),"to",ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); - return Result.ok(info); - }} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java deleted file mode 100644 index 12460c97..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.Status; -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; - -public class URModify extends ActionDAO { - public URModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster,dryRun); - } - - public URModify(AuthzTrans trans, ActionDAO adao) { - super(trans, adao); - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur,Modify modify) { - if (dryRun) { - trans.info().printf("Would Update %s %s", ur.user(), ur.role()); - return Result.ok(); - } else { - Result> rr = q.userRoleDAO.read(trans, ur.user(),ur.role()); - if (rr.notOKorIsEmpty()) { - return Result.err(rr); - } - for (Data d : rr.value) { - modify.change(d); - if (!(ur.expires().equals(d.expires))) { - ur.expires(d.expires); - } - if (ur.user().equals(d.user) && ur.role().equals(d.role)){ - Result rv = q.userRoleDAO.update(trans, d); - if (rv.isOK()) { - trans.info().printf("Updated %s %s to %s", ur.user(), ur.role(), d.toString()); - } else { - trans.info().log(rv.errorString()); - } - } else { - return Result.err(Status.ERR_Denied, "You cannot change the key of this Data"); - } - } - return Result.err(Status.ERR_UserRoleNotFound,"No User Role with %s %s",ur.user(),ur.role()); - } - } - - public static interface Modify { - void change(UserRoleDAO.Data ur); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPrint.java deleted file mode 100644 index be464d42..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPrint.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.util.Chrono; - -public class URPrint implements Action { - private String info; - - public URPrint(String text) { - this.info = text; - } - - @Override - public Result exec(AuthzTrans trans, UserRole ur, String text) { - trans.info().log(info,text,ur.user(),"to",ur.role(),"expiring on",Chrono.dateOnlyStamp(ur.expires())); - return Result.ok(); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java deleted file mode 100644 index 6371ebb5..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions; - -import java.io.IOException; -import java.util.Date; -import java.util.List; - -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.Cluster; - -public class URPunt extends ActionPuntDAO { - public URPunt(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws APIException, IOException { - super(trans,cluster, months, range,dryRun); - } - - public URPunt(AuthzTrans trans, ActionDAO adao, int months, int range) { - super(trans, adao, months, range); - } - - public Result exec(AuthzTrans trans, UserRole ur, String text) { - if (dryRun) { - trans.info().log("Would Update User",ur.user(),"and Role", ur.role(), text); - return Result.ok(); - } else { - Result> read = q.userRoleDAO.read(trans, ur.user(), ur.role()); - if (read.isOK()) { - for (UserRoleDAO.Data data : read.value) { - Date from = data.expires; - data.expires = puntDate(from); - if (data.expires.compareTo(from)<=0) { - trans.debug().printf("Error: %s is same or before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); - } else { - trans.info().log("Updating User",ur.user(),"and Role", ur.role(), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires), text); - q.userRoleDAO.update(trans, data); - } - } - return Result.ok(); - } else { - return Result.err(read); - } - } - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java new file mode 100644 index 00000000..3d742167 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java @@ -0,0 +1,513 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.lang.reflect.Constructor; +import java.net.InetAddress; +import java.net.URL; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.text.SimpleDateFormat; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TimeZone; + +import org.onap.aaf.auth.common.Define; +import org.onap.aaf.auth.dao.CassAccess; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.org.OrganizationFactory; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.Access.Level; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.StaticSlot; +import org.onap.aaf.misc.env.TimeTaken; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.Statement; + +public abstract class Batch { + + private static String rootNs; + + private static StaticSlot ssargs; + + protected static final String STARS = "*****"; + + protected final Cluster cluster; + protected static AuthzEnv env; + protected static Session session; + protected static Set specialNames; + protected static boolean dryRun; + protected static String batchEnv; + + public static final String CASS_ENV = "CASS_ENV"; + public static final String LOG_DIR = "LOG_DIR"; + protected static final String PUNT="punt"; + protected static final String MAX_EMAILS="MAX_EMAILS"; + protected static final String VERSION="VERSION"; + public static final String GUI_URL="GUI_URL"; + + protected final Organization org; + + + + protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException { + // Be able to change Environments + // load extra properties, i.e. + // PERF.cassandra.clusters=.... + batchEnv = env.getProperty(CASS_ENV); + if (batchEnv != null) { + batchEnv = batchEnv.trim(); + env.info().log("Redirecting to ",batchEnv,"environment"); + String str; + for (String key : new String[]{ + CassAccess.CASSANDRA_CLUSTERS, + CassAccess.CASSANDRA_CLUSTERS_PORT, + CassAccess.CASSANDRA_CLUSTERS_USER_NAME, + CassAccess.CASSANDRA_CLUSTERS_PASSWORD, + VERSION,GUI_URL,PUNT,MAX_EMAILS, + LOG_DIR, + "SPECIAL_NAMES" + }) { + if ((str = env.getProperty(batchEnv+'.'+key))!=null) { + env.setProperty(key, str); + } + } + } + + // Setup for Dry Run + cluster = CassAccess.cluster(env,batchEnv); + env.info().log("cluster name - ",cluster.getClusterName()); + String dryRunStr = env.getProperty( "DRY_RUN" ); + if ( dryRunStr == null || "false".equals(dryRunStr.trim()) ) { + dryRun = false; + } else { + dryRun = true; + env.info().log("dryRun set to TRUE"); + } + + org = OrganizationFactory.init(env); + org.setTestMode(dryRun); + + // Special names to allow behaviors beyond normal rules + specialNames = new HashSet<>(); + String names = env.getProperty( "SPECIAL_NAMES" ); + if ( names != null ) + { + env.info().log("Loading SPECIAL_NAMES"); + for (String s :names.split(",") ) + { + env.info().log("\tspecial: " + s ); + specialNames.add( s.trim() ); + } + } + } + + protected abstract void run(AuthzTrans trans); + protected abstract void _close(AuthzTrans trans); + + public String[] args() { + return env.get(ssargs); + } + + public boolean isDryRun() + { + return dryRun; + } + + public boolean isSpecial(String user) { + if (specialNames != null && specialNames.contains(user)) { + env.info().log("specialName: " + user); + + return (true); + } else { + return (false); + } + } + + + protected PrintStream fallout(PrintStream inFallout, String logType) + throws IOException { + PrintStream fallout = inFallout; + if (fallout == null) { + File dir = new File("logs"); + if (!dir.exists()) { + dir.mkdirs(); + } + + File f = null; + long uniq = System.currentTimeMillis(); + + f = new File(dir, getClass().getSimpleName() + "_" + logType + "_" + + uniq + ".log"); + + fallout = new PrintStream(new FileOutputStream(f, true)); + } + return fallout; + } + + public Organization getOrgFromID(AuthzTrans trans, String user) { + Organization organization; + try { + organization = OrganizationFactory.obtain(trans.env(),user.toLowerCase()); + } catch (OrganizationException e1) { + trans.error().log(e1); + organization=null; + } + + if (organization == null) { + PrintStream fallout = null; + + try { + fallout = fallout(fallout, "Fallout"); + fallout.print("INVALID_ID,"); + fallout.println(user); + } catch (Exception e) { + env.error().log("Could not write to Fallout File", e); + } + return (null); + } + + return (organization); + } + + public static Row executeDeleteQuery(Statement stmt) { + Row row = null; + if (!dryRun) { + row = session.execute(stmt).one(); + } + + return (row); + + } + + public static int acquireRunLock(String className) { + Boolean testEnv = true; + String envStr = env.getProperty("AFT_ENVIRONMENT"); + + if (envStr != null) { + if ("AFTPRD".equals(envStr)) { + testEnv = false; + } + } else { + env.fatal() + .log("AFT_ENVIRONMENT property is required and was not found. Exiting."); + System.exit(1); + } + + if (testEnv) { + env.info().log("TESTMODE: skipping RunLock"); + return (1); + } + + String hostname = null; + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + e.printStackTrace(); + env.warn().log("Unable to get hostname"); + return (0); + } + + ResultSet existing = session.execute(String.format( + "select * from authz.run_lock where class = '%s'", className)); + + for (Row row : existing) { + long curr = System.currentTimeMillis(); + ByteBuffer lastRun = row.getBytesUnsafe(2); // Can I get this field + // by name? + + long interval = (1 * 60 * 1000); // @@ Create a value in props file + // for this + long prev = lastRun.getLong(); + + if ((curr - prev) <= interval) { + env.warn().log( + String.format("Too soon! Last run was %d minutes ago.", + ((curr - prev) / 1000) / 60)); + env.warn().log( + String.format("Min time between runs is %d minutes ", + (interval / 1000) / 60)); + env.warn().log( + String.format("Last ran on machine: %s at %s", + row.getString("host"), row.getDate("start"))); + return (0); + } else { + env.info().log("Delete old lock"); + deleteLock(className); + } + } + + GregorianCalendar current = new GregorianCalendar(); + + // We want our time in UTC, hence "+0000" + SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000"); + fmt.setTimeZone(TimeZone.getTimeZone("UTC")); + + String cql = String + .format("INSERT INTO authz.run_lock (class,host,start) VALUES ('%s','%s','%s') IF NOT EXISTS", + className, hostname, fmt.format(current.getTime())); + + env.info().log(cql); + + Row row = session.execute(cql).one(); + if (!row.getBool("[applied]")) { + env.warn().log("Lightweight Transaction failed to write lock."); + env.warn().log( + String.format("host with lock: %s, running at %s", + row.getString("host"), row.getDate("start"))); + return (0); + } + return (1); + } + + private static void deleteLock( String className) { + Row row = session.execute( String.format( "DELETE FROM authz.run_lock WHERE class = '%s' IF EXISTS", className ) ).one(); + if (! row.getBool("[applied]")) { + env.info().log( "delete failed" ); + } + } + + private static void transferVMProps(AuthzEnv env, String ... props) { + String value; + for (String key : props) { + if ((value = System.getProperty(key))!=null) { + env.setProperty(key, value); + } + } + } + + // IMPORTANT! VALIDATE Organization isUser method + protected void checkOrganizationAcccess(AuthzTrans trans, Question q) throws APIException, OrganizationException { + Set testUsers = new HashSet<>(); + Result> rrd = q.roleDAO.readNS(trans, rootNs); + if (rrd.isOK()) { + for (RoleDAO.Data r : rrd.value) { + Result> rur = q.userRoleDAO.readByRole(trans, r.fullName()); + if (!rur.isOK()) { + continue; + } + for (UserRoleDAO.Data udd : rur.value) { + testUsers.add(udd.user); + } + } + if (testUsers.size() < 2) { + throw new APIException("Not enough Users in Roles for " + rootNs + " to Validate"); + } + + Identity iden; + for (String user : testUsers) { + if ((iden = org.getIdentity(trans, user)) == null) { + throw new APIException("Failed Organization Entity Validation Check: " + user); + } else { + trans.info().log("Organization Validation Check: " + iden.id()); + } + } + } + } + + protected static String logDir() { + String ld = env.getProperty(LOG_DIR); + if (ld==null) { + if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir + ld = "logs/"; + } else { + ld = "logs/"+batchEnv; + } + } + return ld; + } + protected int count(String str, char c) { + if (str==null || str.isEmpty()) { + return 0; + } else { + int count=1; + for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) { + ++count; + } + return count; + } + } + + public final void close(AuthzTrans trans) { + _close(trans); + cluster.close(); + } + + public static void main(String[] args) { + PropAccess access = new PropAccess(args); + InputStream is = null; + String filename; + String propLoc; + try { + Define.set(access); + rootNs =Define.ROOT_NS(); + if(access.getProperty(Config.CADI_PROP_FILES)==null) { + File f = new File("authBatch.props"); + try { + if (f.exists()) { + filename = f.getAbsolutePath(); + is = new FileInputStream(f); + propLoc = f.getPath(); + } else { + URL rsrc = ClassLoader.getSystemResource("authBatch.props"); + filename = rsrc.toString(); + is = rsrc.openStream(); + propLoc = rsrc.getPath(); + } + access.load(is); + } finally { + if (is == null) { + System.err.println("authBatch.props must exist in current dir, or in Classpath"); + System.exit(1); + } + is.close(); + } + if (filename != null) { + access.log(Level.INFO,"Instantiated properties from", filename); + } + + // Log where Config found + access.log(Level.INFO,"Configuring from", propLoc); + + } + env = new AuthzEnv(access); + + transferVMProps(env, CASS_ENV, "DRY_RUN", "NS", "Organization"); + + // Flow all Env Logs to Log4j, with ENV + +// LogFileNamer lfn; +// lfn = new LogFileNamer(logDir(),"").noPID(); +// lfn.setAppender("authz-batch"); +// lfn.setAppender("aspr|ASPR"); +// lfn.setAppender("sync"); +// lfn.setAppender("jobchange"); +// lfn.setAppender("validateuser"); +// aspr = Logger.getLogger("aspr"); +// Log4JLogTarget.setLog4JEnv("authz-batch", env); +// propLoc = null; + + Batch batch = null; + // setup ATTUser and Organization Slots before starting this: + // TODO redo this + // env.slot(ATT.ATT_USERSLOT); + // + // OrganizationFactory.setDefaultOrg(env, ATT.class.getName()); + AuthzTrans trans = env.newTrans(); + + TimeTaken tt = trans.start("Total Run", Env.SUB); + try { + int len = args.length; + if (len > 0) { + String toolName = args[0]; + len -= 1; + if (len < 0) + len = 0; + String nargs[] = new String[len]; + if (len > 0) { + System.arraycopy(args, 1, nargs, 0, len); + } + + env.put(ssargs = env.staticSlot("ARGS"), nargs); + + /* + * Add New Batch Programs (inherit from Batch) here + */ + + // Might be a Report, Update or Temp Batch + Class cls; + String classifier = ""; + try { + cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.update." + toolName); + classifier = "Update:"; + } catch (ClassNotFoundException e) { + try { + cls = ClassLoader.getSystemClassLoader().loadClass("org.onap.aaf.auth.reports." + toolName); + classifier = "Report:"; + } catch (ClassNotFoundException e2) { + try { + cls = ClassLoader.getSystemClassLoader() + .loadClass("org.onap.aaf.auth.temp." + toolName); + classifier = "Temp Utility:"; + } catch (ClassNotFoundException e3) { + cls = null; + } + } + } + if (cls != null) { + Constructor cnst = cls.getConstructor(new Class[] { AuthzTrans.class }); + batch = (Batch) cnst.newInstance(trans); + env.info().log("Begin", classifier, toolName); + } + + + if (batch == null) { + trans.error().log("No Batch named", toolName, "found"); + } + /* + * End New Batch Programs (inherit from Batch) here + */ + + } + if (batch != null) { + batch.run(trans); + } + } finally { + tt.done(); + if (batch != null) { + batch.close(trans); + } + StringBuilder sb = new StringBuilder("Task Times\n"); + trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE); + trans.info().log(sb); + } + } catch (Exception e) { + e.printStackTrace(System.err); + // Exceptions thrown by DB aren't stopping the whole process. + System.exit(1); + } + } + +} + diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchException.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchException.java new file mode 100644 index 00000000..dbb2dc31 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchException.java @@ -0,0 +1,51 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch; + +public class BatchException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -3877245367723491192L; + + public BatchException() { + } + + public BatchException(String message) { + super(message); + } + + public BatchException(Throwable cause) { + super(cause); + } + + public BatchException(String message, Throwable cause) { + super(message, cause); + } + + public BatchException(String message, Throwable cause, + boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchPrincipal.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchPrincipal.java new file mode 100644 index 00000000..0bc58add --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/BatchPrincipal.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ +package org.onap.aaf.auth.batch; + +import org.onap.aaf.cadi.principal.TaggedPrincipal; + +public class BatchPrincipal extends TaggedPrincipal { + private final String name; + + public BatchPrincipal(final String name) { + this.name = "batch:"+name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String tag() { + return "Btch"; + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/CassBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/CassBatch.java new file mode 100644 index 00000000..1fc16e4e --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/CassBatch.java @@ -0,0 +1,82 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch; + +import java.io.IOException; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.impl.Log4JLogTarget; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.exceptions.InvalidQueryException; + +public abstract class CassBatch extends Batch { + + protected CassBatch(AuthzTrans trans, String log4JName) throws APIException, IOException, OrganizationException { + super(trans.env()); + // Flow all Env Logs to Log4j + Log4JLogTarget.setLog4JEnv(log4JName, env); + + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + } + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + trans.info().log("Closed Session"); + } + + public ResultSet executeQuery(String cql) { + return executeQuery(cql,""); + } + + public ResultSet executeQuery(String cql, String extra) { + if (isDryRun() && !cql.startsWith("SELECT")) { + if (extra!=null) { + env.info().log("Would query" + extra + ": " + cql); + } + } else { + if (extra!=null) { + env.info().log("query" + extra + ": " + cql); + } + try { + return session.execute(cql); + } catch (InvalidQueryException e) { + if (extra==null) { + env.info().log("query: " + cql); + } + throw e; + } + } + return null; + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Action.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Action.java new file mode 100644 index 00000000..544d049d --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Action.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; + +public interface Action { + public Result exec(AuthzTrans trans, D data, T t); +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionDAO.java new file mode 100644 index 00000000..416a13ce --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionDAO.java @@ -0,0 +1,73 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.dao.CassAccess; +import org.onap.aaf.auth.dao.hl.Function; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +public abstract class ActionDAO implements Action { + protected final Question q; + protected final Function f; + private boolean clean; + protected final boolean dryRun; + + public ActionDAO(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + q = new Question(trans, cluster, CassAccess.KEYSPACE, false); + f = new Function(trans,q); + clean = true; + this.dryRun = dryRun; + } + + public ActionDAO(AuthzTrans trans, ActionDAO predecessor) { + q = predecessor.q; + f = new Function(trans,q); + clean = false; + dryRun = predecessor.dryRun; + } + + public Session getSession(AuthzTrans trans) throws APIException, IOException { + return q.historyDAO.getSession(trans); + } + + public Question question() { + return q; + } + + public Function function() { + return f; + } + + public void close(AuthzTrans trans) { + if (clean) { + q.close(trans); + } + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionPuntDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionPuntDAO.java new file mode 100644 index 00000000..37abbaf4 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/ActionPuntDAO.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public abstract class ActionPuntDAO extends ActionDAO { + private int months; + protected static final Date now = new Date(); + + public ActionPuntDAO(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + this.months = months; + } + + public ActionPuntDAO(AuthzTrans trans, ActionDAO predecessor, int months, int range) { + super(trans, predecessor); + this.months = months; + } + + + protected Date puntDate(Date current) { + GregorianCalendar temp = new GregorianCalendar(); + temp.setTime(current); + temp.add(GregorianCalendar.MONTH, months); + + /* + * This method Randomized date. This is no longer needed. Just add the Punt Months. + temp.add(GregorianCalendar.MONTH, months); + if (range>0) { + int forward = Math.abs(random.nextInt()%range); + if (forward>1) { + temp.add(GregorianCalendar.MONTH, forward); + temp.add(GregorianCalendar.DAY_OF_MONTH, (random.nextInt()%30)-15); + } + } + */ + return temp.getTime(); + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CacheTouch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CacheTouch.java new file mode 100644 index 00000000..a4f4dcf3 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CacheTouch.java @@ -0,0 +1,53 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class CacheTouch extends ActionDAO { + + public CacheTouch(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public CacheTouch(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, String table, String text) { + if (dryRun) { + trans.info().printf("Would mark %s cache in DB for clearing: %s",table, text); + return Result.ok(); + } else { + Result rv = q.clearCache(trans, table); + trans.info().printf("Set DB Cache %s for clearing: %s",table, text); + return rv; + } + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredDelete.java new file mode 100644 index 00000000..61da6094 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredDelete.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class CredDelete extends ActionDAO { + + public CredDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public CredDelete(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, CredDAO.Data cred, String text) { + if (dryRun) { + trans.info().log("Would Delete:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); + return Result.ok(); + } else { + Result rv = q.credDAO.delete(trans, cred, true); // need to read for undelete + trans.info().log("Deleted:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); + return rv; + } + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPrint.java new file mode 100644 index 00000000..9780f2ba --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPrint.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.util.Chrono; + +public class CredPrint implements Action { + private String info; + + public CredPrint(String text) { + this.info = text; + } + + @Override + public Result exec(AuthzTrans trans, CredDAO.Data cred, String text) { + trans.info().log(info,cred.id,text, type(cred.type),Chrono.dateOnlyStamp(cred.expires)); + return Result.ok(); + } + + + public static String type(int type) { + switch(type) { + case CredDAO.BASIC_AUTH: // 1 + return "OLD"; + case CredDAO.BASIC_AUTH_SHA256: // 2 + return "U/P"; + case CredDAO.CERT_SHA256_RSA: // 200 + return "Cert"; + default: + return "Unknown"; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPunt.java new file mode 100644 index 00000000..ef6bb94e --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/CredPunt.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.Date; +import java.util.List; + +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class CredPunt extends ActionPuntDAO { + + public CredPunt(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws IOException, APIException { + super(trans,cluster,months,range,dryRun); + } + + public CredPunt(AuthzTrans trans, ActionDAO adao, int months, int range) throws IOException { + super(trans, adao, months,range); + } + + public Result exec(AuthzTrans trans, CredDAO.Data cdd,String text) { + Result rv = null; + Result> read = q.credDAO.read(trans, cdd); + if (read.isOKhasData()) { + for (CredDAO.Data data : read.value) { + Date from = data.expires; + data.expires = puntDate(from); + if (data.expires.compareTo(from)<=0) { + trans.debug().printf("Error: %s is before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); + } else { + if (dryRun) { + trans.info().log("Would Update Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); + } else { + trans.info().log("Updated Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); + rv = q.credDAO.update(trans, data); + } + } + } + } + if (rv==null) { + rv=Result.err(read); + } + return rv; + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Email.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Email.java new file mode 100644 index 00000000..461d3fc7 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Email.java @@ -0,0 +1,217 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.misc.env.util.Chrono; + +public class Email implements Action{ + protected final List toList; + protected final List ccList; + private final String[] defaultCC; + protected String subject; + private String preamble; + private Message msg; + private String sig; + protected String lineIndent=" "; + private long lastSent=0L; + + + public Email(String ... defaultCC) { + toList = new ArrayList<>(); + this.defaultCC = defaultCC; + ccList = new ArrayList<>(); + clear(); + } + + public Email clear() { + toList.clear(); + ccList.clear(); + for (String s: defaultCC) { + ccList.add(s); + } + return this; + } + + + public void indent(String indent) { + lineIndent = indent; + } + + public void preamble(String format, Object ... args) { + preamble = String.format(format, args); + } + + public Email addTo(Identity id) { + if (id!=null && !toList.contains(id.email())) { + toList.add(id.email()); + } + return this; + } + + public Email addTo(Collection users) { + for (String u : users) { + addTo(u); + } + return this; + } + + public Email addTo(String email) { + if (!toList.contains(email)) { + toList.add(email); + } + return this; + } + + public Email addCC(Identity id) { + if (id!=null && !ccList.contains(id.email())) { + ccList.add(id.email()); + } + return this; + } + + public Email addCC(String email) { + if (!ccList.contains(email)) { + ccList.add(email); + } + return this; + } + + + public Email add(Identity id, boolean toSuper) throws OrganizationException { + Identity responsible = id.responsibleTo(); + if (toSuper) { + addTo(responsible.email()); + addCC(id.email()); + } else { + addCC(responsible.email()); + addTo(id.email()); + } + return this; + } + + public Email subject(String format, Object ... args) { + if (format.contains("%s")) { + subject = String.format(format, args); + } else { + subject = format; + } + return this; + } + + + public Email signature(String format, Object ... args) { + sig = String.format(format, args); + return this; + } + + public void msg(Message msg) { + this.msg = msg; + } + + @Override + public Result exec(AuthzTrans trans, Organization org, String text) { + StringBuilder sb = new StringBuilder(); + if (preamble!=null) { + sb.append(lineIndent); + sb.append(preamble); + sb.append("\n\n"); + } + + if (msg!=null) { + msg.msg(sb,lineIndent); + sb.append("\n"); + } + + if (sig!=null) { + sb.append(sig); + sb.append("\n"); + } + + long ct = System.currentTimeMillis(); + long wait = ct-lastSent; + lastSent = ct; + if (wait < 100) { // 10 per second + try { + Thread.sleep(wait); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return exec(trans,org,sb); + } + + protected Result exec(AuthzTrans trans, Organization org, StringBuilder sb) { + try { + /* int status = */ + org.sendEmail(trans, + toList, + ccList, + subject, + sb.toString(), + false); + } catch (Exception e) { + return Result.err(Result.ERR_ActionNotCompleted,e.getMessage()); + } + return Result.ok(); + + } + + public void log(PrintStream ps, String text) { + ps.print(Chrono.dateTime()); + boolean first = true; + for (String s : toList) { + if (first) { + first = false; + ps.print(": "); + } else { + ps.print(", "); + } + ps.print(s); + } + if (!ccList.isEmpty()) { + first=true; + for (String s : ccList) { + if (first) { + first = false; + ps.print(" ["); + } else { + ps.print(", "); + } + ps.print(s); + } + ps.print(']'); + } + + ps.print(' '); + ps.println(text); + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/EmailPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/EmailPrint.java new file mode 100644 index 00000000..3ab481f5 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/EmailPrint.java @@ -0,0 +1,98 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.PrintStream; + +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization; + +public class EmailPrint extends Email { + + private static final int LINE_LENGTH = 100; + + public EmailPrint(String... defaultCC) { + super(defaultCC); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.actions.Email#exec(org.onap.aaf.auth.org.test.Organization, java.lang.StringBuilder) + */ + @Override + protected Result exec(AuthzTrans trans, Organization org, StringBuilder msg) { + PrintStream out = System.out; + boolean first = true; + out.print("To: "); + for (String s: toList) { + if (first) {first = false;} + else {out.print(',');} + out.print(s); + } + out.println(); + + first = true; + out.print("CC: "); + for (String s: ccList) { + if (first) {first = false;} + else {out.print(',');} + out.print(s); + } + out.println(); + + out.print("Subject: "); + out.println(subject); + out.println(); + boolean go = true; + + for (int start=0, end=LINE_LENGTH;go;start=end,end=Math.min(msg.length(), start+LINE_LENGTH)) { + int ret = msg.indexOf("\n",start+1); + switch(ret) { + case -1: + out.println(msg.substring(start,end)); + break; + case 0: + end=start+1; + out.println(); + break; + default: + if (retstart && ret { + private String info; + + public FuturePrint(String text) { + this.info = text; + } + + @Override + public Result exec(AuthzTrans trans, Future f, String text) { + trans.info().log(info,f.id(),f.memo(),"expiring on",Chrono.dateOnlyStamp(f.expires())); + return Result.ok(); + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Key.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Key.java new file mode 100644 index 00000000..fb43a425 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Key.java @@ -0,0 +1,26 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +public interface Key { + public String key(HELPER H); +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Message.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Message.java new file mode 100644 index 00000000..8bef131c --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/Message.java @@ -0,0 +1,53 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.util.ArrayList; +import java.util.List; + +public class Message { + public final List lines; + + public Message() { + lines = new ArrayList<>(); + } + + public void clear() { + lines.clear(); + } + + public String line(String format, Object ... args) { + String rv=String.format(format, args); + lines.add(rv); + return rv; + } + + public void msg(StringBuilder sb, String lineIndent) { + if (!lines.isEmpty()) { + for (String line : lines) { + sb.append(lineIndent); + sb.append(line); + sb.append('\n'); + } + } + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSACreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSACreate.java new file mode 100644 index 00000000..567bccfc --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSACreate.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.NsAttrib; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class NSACreate extends ActionDAO { + public NSACreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public NSACreate(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { + if (dryRun) { + trans.info().printf("Would Create %s Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); + return Result.ok(); + } else { + Result rv = q.nsDAO.dao().attribAdd(trans, nsa.ns, nsa.key, nsa.value); + if (rv.isOK()) { + trans.info().printf("%s - Created Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); + } else { + trans.error().printf("Error Creating Attrib '%s=%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSADelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSADelete.java new file mode 100644 index 00000000..86eff7ea --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSADelete.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.NsAttrib; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class NSADelete extends ActionDAO { + public NSADelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public NSADelete(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { + if (dryRun) { + trans.info().printf("Would Delete %s Attrib '%s' in %s",text,nsa.key,nsa.ns); + return Result.ok(); + } else { + Result rv = q.nsDAO.dao().attribRemove(trans, nsa.ns, nsa.key); + if (rv.isOK()) { + trans.info().printf("%s - Deleted Attrib '%s' in %s",text,nsa.key,nsa.value,nsa.ns); + } else { + trans.error().printf("Error Deleting Attrib '%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSDescUpdate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSDescUpdate.java new file mode 100644 index 00000000..2542e045 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/NSDescUpdate.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.NS; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class NSDescUpdate extends ActionDAO { + public NSDescUpdate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public NSDescUpdate(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, NS ns, String desc) { + if (dryRun) { + trans.info().printf("Would Update '%s' Description to '%s'",ns,desc); + return Result.ok(); + } else { + Result rv = q.nsDAO.dao().addDescription(trans, ns.name, desc); + if (rv.isOK()) { + trans.info().printf("Updated '%s' Description to '%s'",ns,desc); + } else { + trans.error().printf("Error Updating '%s' Description to '%s' - %s",ns,desc,rv.details); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermCreate.java new file mode 100644 index 00000000..65555704 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermCreate.java @@ -0,0 +1,69 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.Perm; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.PermDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + + +public class PermCreate extends ActionDAO { + public PermCreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public PermCreate(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, Perm p,String text) { + PermDAO.Data pdd = new PermDAO.Data(); + pdd.ns = p.ns; + pdd.type = p.type; + pdd.instance = p.instance; + pdd.action = p.action; + pdd.description = p.description; + pdd.roles = p.roles; + + if (dryRun) { + trans.info().log("Would Create Perm:",text,p.fullType()); + return Result.ok(pdd); + } else { + Result rv = q.permDAO.create(trans, pdd); // need to read for undelete + if (rv.isOK()) { + trans.info().log("Created Perm:",text,p.fullType()); + } else { + trans.error().log("Error Creating Role -",rv.details,":",p.fullType()); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermDelete.java new file mode 100644 index 00000000..b9ae8d56 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermDelete.java @@ -0,0 +1,64 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.Perm; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class PermDelete extends ActionDAO { + public PermDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public PermDelete(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, Perm p,String text) { + PermDAO.Data pdd = new PermDAO.Data(); + pdd.ns = p.ns; + pdd.type = p.type; + pdd.instance = p.instance; + pdd.action = p.action; + if (dryRun) { + trans.info().log("Would Delete Perm:",text,p.fullType()); + return Result.ok(); + } else { + Result rv = q.permDAO.delete(trans, pdd, true); // need to read for undelete + if (rv.isOK()) { + trans.info().log("Deleted Perm:",text,p.fullType()); + } else { + trans.error().log("Error Deleting Perm -",rv.details,":",p.fullType()); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermModify.java new file mode 100644 index 00000000..4b76baf5 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/PermModify.java @@ -0,0 +1,141 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.List; + +import org.onap.aaf.auth.batch.helpers.Perm; +import org.onap.aaf.auth.batch.helpers.Role; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.cass.PermDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class PermModify extends ActionDAO { + public PermModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public PermModify(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, final Perm p, final Modify modify) { + Result> rr = q.permDAO.read(trans, p.ns,p.type,p.instance,p.action); + if (dryRun) { + if (rr.isOKhasData()) { + return Result.ok(rr.value.get(0)); + } else { + return Result.err(Result.ERR_NotFound, "Data not Found " + p.toString()); + } + } else { + Result rv = null; + if (rr.isOKhasData()) { + for (final Data d : rr.value) { + modify.change(d); + if (d.ns.equals(p.ns) && d.type.equals(p.type) && d.instance.equals(p.instance) && d.action.equals(p.action)) { + // update for fields + // In either case, adjust Permissions + for (String r : d.roles) { + if (!p.roles.contains(r)) { + q.permDAO.dao().addRole(trans, d, r); + } + } + for (String r : p.roles) { + if (!d.roles.contains(r)) { + q.permDAO.dao().delRole(trans, d, r); + } + } + rv = Result.ok(d); + } else { + for (String r : d.roles) { + Role role = Role.keys.get(r); + if (role.perms.contains(p.encode())) { + modify.roleModify().exec(trans, role, new RoleModify.Modify() { + @Override + public PermModify permModify() { + return PermModify.this; + } + + @Override + public void change(RoleDAO.Data rdd) { + rdd.perms.remove(p.encode()); + rdd.perms.add(d.encode()); + } + }); + } + } + + rv = q.permDAO.create(trans, d); + if (rv.isOK()) { + PermDAO.Data pdd = new PermDAO.Data(); + pdd.ns = p.ns; + pdd.type = p.type; + pdd.instance = p.instance; + pdd.action = p.action; + q.permDAO.delete(trans, pdd, false); + trans.info().printf("Updated %s|%s|%s|%s to %s|%s|%s|%s\n", + p.ns, p.type, p.instance, p.action, + d.ns, d.type, d.instance, d.action); + } else { + trans.info().log(rv.errorString()); + } + } + + } + } else { + rv = Result.err(rr); + } + if (rv==null) { + rv = Result.err(Status.ERR_General,"Never get to this code"); + } + + return rv; + } + } + + public static interface Modify { + void change(PermDAO.Data ur); + RoleModify roleModify(); + } + + public Result delete(AuthzTrans trans, Perm p) { + if (dryRun) { + return Result.ok(); + } else { + PermDAO.Data data = new PermDAO.Data(); + data.ns=p.ns; + data.type = p.type; + data.instance = p.instance; + data.action = p.action; + return q.permDAO.delete(trans,data,false); + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleCreate.java new file mode 100644 index 00000000..512d4a31 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleCreate.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.Role; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class RoleCreate extends ActionDAO { + public RoleCreate(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public RoleCreate(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, Role r,String text) { + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns = r.ns; + rdd.name = r.name; + rdd.description = r.description; + rdd.perms = r.perms; + + if (dryRun) { + trans.info().log("Would Create Role:",text,r.fullName()); + return Result.ok(rdd); + } else { + Result rv = q.roleDAO.create(trans, rdd); // need to read for undelete + if (rv.isOK()) { + trans.info().log("Created Role:",text,r.fullName()); + } else { + trans.error().log("Error Creating Role -",rv.details,":",r.fullName()); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleDelete.java new file mode 100644 index 00000000..3e109b2b --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleDelete.java @@ -0,0 +1,62 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.Role; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class RoleDelete extends ActionDAO { + public RoleDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public RoleDelete(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, Role r,String text) { + if (dryRun) { + trans.info().log("Would Delete Role:",text,r.fullName()); + return Result.ok(); + } else { + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns = r.ns; + rdd.name = r.name; + Result rv = q.roleDAO.delete(trans, rdd, true); // need to read for undelete + if (rv.isOK()) { + trans.info().log("Deleted Role:",text,r.fullName()); + } else { + trans.error().log("Error Deleting Role -",rv.details,":",r.fullName()); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleModify.java new file mode 100644 index 00000000..388e6692 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/RoleModify.java @@ -0,0 +1,152 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.List; + +import org.onap.aaf.auth.batch.helpers.Perm; +import org.onap.aaf.auth.batch.helpers.Role; +import org.onap.aaf.auth.dao.cass.PermDAO; +import org.onap.aaf.auth.dao.cass.RoleDAO; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.cass.RoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class RoleModify extends ActionDAO { + public RoleModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + } + + public RoleModify(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(final AuthzTrans trans, final Role r,final RoleModify.Modify modify) { + Result> rr = q.roleDAO.read(trans, r.ns,r.name); + if (dryRun) { + if (rr.isOKhasData()) { + return Result.ok(rr.value.get(0)); + } else { + return Result.err(Result.ERR_NotFound, "Data not Found " + r.toString()); + } + } else { + Result rv = null; + if (rr.isOKhasData()) { + for (final Data d : rr.value) { + modify.change(d); + if (d.ns.equals(r.ns) && d.name.equals(r.name)) { + // update for fields + // In either case, adjust Roles + for (String p : d.perms) { + if (!r.perms.contains(p)) { + Result rpdd = PermDAO.Data.decode(trans, q, p); + if (rpdd.isOKhasData()) { + q.roleDAO.dao().addPerm(trans, d, rpdd.value); + } + } + } + for (String p : r.perms) { + if (!d.perms.contains(p)) { + Result rpdd = PermDAO.Data.decode(trans, q, p); + if (rpdd.isOKhasData()) { + q.roleDAO.dao().delPerm(trans, d, rpdd.value); + } + } + } + rv = Result.ok(d); + } else { + for (String p : d.perms) { + Perm perm = Perm.keys.get(p); + if (perm!=null) { + if (perm.roles.contains(r.encode())) { + modify.permModify().exec(trans, perm, new PermModify.Modify() { + @Override + public RoleModify roleModify() { + return RoleModify.this; + } + + @Override + public void change(PermDAO.Data pdd) { + pdd.roles.remove(r.encode()); + pdd.roles.add(d.encode()); + } + }); + } + } + } + Result> preexist = q.roleDAO.read(trans, d); + if (preexist.isOKhasData()) { + Data rdd = preexist.value.get(0); + for (String p : d.perms) { + Result perm = PermDAO.Data.decode(trans, q, p); + if (perm.isOKhasData()) { + q.roleDAO.dao().addPerm(trans,rdd, perm.value); + } + } + rv = Result.ok(rdd); + } else { + rv = q.roleDAO.create(trans, d); + } + if (rv.isOK()) { + trans.info().printf("Updating %s|%s to %s|%s", r.ns, r.name, d.ns, d.name); + RoleDAO.Data rmme = new RoleDAO.Data(); + rmme.ns=r.ns; + rmme.name=r.name; + q.roleDAO.delete(trans, rmme, false); + + } else { + trans.info().log(rv.errorString()); + } + } + } + } else { + rv = Result.err(rr); + } + if (rv==null) { + rv = Result.err(Status.ERR_General,"Never get to this code"); + } + return rv; + } + } + + public static interface Modify { + void change(RoleDAO.Data ur); + PermModify permModify(); + } + + public Result delete(AuthzTrans trans, Role r) { + if (dryRun) { + return Result.ok(); + } else { + RoleDAO.Data data = new RoleDAO.Data(); + data.ns=r.ns; + data.name = r.name; + return q.roleDAO.delete(trans,data,false); + } + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URAdd.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URAdd.java new file mode 100644 index 00000000..e0c1bb80 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URAdd.java @@ -0,0 +1,57 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class URAdd extends ActionDAO { + public URAdd(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public URAdd(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur, String text) { + if (dryRun) { + trans.info().log("Would Add:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); + return Result.ok(ur.urdd()); + } else { + Result rv = q.userRoleDAO.create(trans, ur.urdd()); + trans.info().log("Added:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URDelete.java new file mode 100644 index 00000000..00208ad9 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URDelete.java @@ -0,0 +1,59 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class URDelete extends ActionDAO { + public URDelete(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public URDelete(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur,String text) { + if (dryRun) { + trans.info().log("Would Delete UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); + return Result.ok(); + } else { + Result rv = q.userRoleDAO.delete(trans,ur.urdd(), true); // need to read for undelete + if (rv.isOK()) { + trans.info().log("Deleted UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); + } else { + trans.error().log("Error Deleting User Role -",rv.details,":",ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires()) ); + } + return rv; + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApprove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApprove.java new file mode 100644 index 00000000..a228a8ca --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApprove.java @@ -0,0 +1,112 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.onap.aaf.auth.batch.helpers.Approval; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.dao.cass.NsDAO; +import org.onap.aaf.auth.dao.hl.Function; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.Organization.Expiration; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class URFutureApprove extends ActionDAO implements Action, Key { + private final Date start; + private final Date expires; + + public URFutureApprove(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans,cluster, dryRun); + GregorianCalendar gc = new GregorianCalendar(); + start = gc.getTime(); + expires = trans.org().expiration(gc, Expiration.Future).getTime(); + } + + public URFutureApprove(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + GregorianCalendar gc = new GregorianCalendar(); + start = gc.getTime(); + expires = trans.org().expiration(gc, Expiration.Future).getTime(); + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur,String text) { + if (dryRun) { + return Result.ok(text); + } else { + Result rns = q.deriveNs(trans, ur.ns()); + if (rns.isOK()) { + + FutureDAO.Data data = new FutureDAO.Data(); + data.id=null; // let Create function assign UUID + data.target=Function.FOP_USER_ROLE; + + data.memo = key(ur); + data.start = start; + data.expires = ur.expires(); + try { + data.construct = ur.urdd().bytify(); + } catch (IOException e) { + return Result.err(e); + } + Result rfuture = f.createFuture(trans, data, Function.FOP_USER_ROLE, ur.user(), rns.value, FUTURE_OP.A); + if (rfuture.isOK()) { + trans.info().log(rfuture.value, text, ur.user(), data.memo); + } else { + trans.error().log(rfuture.details, text); + } + return rfuture; + } else { + return Result.err(rns); + } + } + } + + @Override + public String key(UserRole ur) { + String expire; + if (expires.before(start)) { + expire = "' - EXPIRED "; + } else { + expire = "' - expiring "; + } + + if (Question.OWNER.equals(ur.rname())) { + return Approval.RE_VALIDATE_OWNER + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); + } else if (Question.ADMIN.equals(ur.rname())) { + return Approval.RE_VALIDATE_ADMIN + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); + } else { + return Approval.RE_APPROVAL_IN_ROLE + ur.role() + expire + Chrono.dateOnlyStamp(ur.expires()); + } + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApproveExec.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApproveExec.java new file mode 100644 index 00000000..631a8115 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFutureApproveExec.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.aaf.auth.batch.helpers.Approval; +import org.onap.aaf.auth.batch.helpers.Future; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.ApprovalDAO.Data; +import org.onap.aaf.auth.dao.hl.Function.FUTURE_OP; +import org.onap.aaf.auth.dao.hl.Function.Lookup; +import org.onap.aaf.auth.dao.hl.Function.OP_STATUS; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class URFutureApproveExec extends ActionDAO, OP_STATUS, Future> { + + public URFutureApproveExec(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans,cluster, dryRun); + } + + public URFutureApproveExec(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, List app, Future future) { + if (dryRun) { + return Result.err(Result.ERR_ActionNotCompleted,"Not Executed"); + } else { + // Save on Lookups + final List apprs = new ArrayList<>(); + final List urs = new ArrayList<>(); + for (Approval a : app) { + apprs.add(a.add); + UserRole ur = UserRole.get(a.add.user, future.role); + if (ur!=null) { + urs.add(ur.urdd()); + } + } + Result rv = f.performFutureOp(trans, FUTURE_OP.A, future.fdd, + new Lookup>() { + @Override + public List get(AuthzTrans trans, Object ... noop) { + return apprs; + } + }, + new Lookup() { + @Override + public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { + List lur = UserRole.getByUser().get(keys[0]); + if (lur!=null) { + for (UserRole ur : lur) { + if (ur.role().equals(keys[1])) { + return ur.urdd(); + } + } + } + return null; + } + }); + if (rv.isOK()) { + switch(rv.value) { + case D: + trans.info().printf("Denied %s on %s", future.memo(),future.fdd.target); + break; + case E: + trans.info().printf("Completed %s on %s", future.memo(),future.fdd.target); + break; + case L: + trans.info().printf("Future %s on %s has lapsed", future.memo(),future.fdd.target); + break; + default: + } + } else { + trans.error().log("Error completing",future.memo(),rv.errorString()); + } + return rv; + } + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFuturePrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFuturePrint.java new file mode 100644 index 00000000..bf6ead36 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URFuturePrint.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.util.Chrono; + + +public class URFuturePrint implements Action { + private String info; + + public URFuturePrint(String text) { + this.info = text; + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur, String text) { + trans.info().log(info,text,ur.user(),"to",ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); + return Result.ok(info); + }} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URModify.java new file mode 100644 index 00000000..a17c4fd2 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URModify.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.List; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.dao.cass.Status; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; + +public class URModify extends ActionDAO { + public URModify(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster,dryRun); + } + + public URModify(AuthzTrans trans, ActionDAO adao) { + super(trans, adao); + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur,Modify modify) { + if (dryRun) { + trans.info().printf("Would Update %s %s", ur.user(), ur.role()); + return Result.ok(); + } else { + Result> rr = q.userRoleDAO.read(trans, ur.user(),ur.role()); + if (rr.notOKorIsEmpty()) { + return Result.err(rr); + } + for (Data d : rr.value) { + modify.change(d); + if (!(ur.expires().equals(d.expires))) { + ur.expires(d.expires); + } + if (ur.user().equals(d.user) && ur.role().equals(d.role)){ + Result rv = q.userRoleDAO.update(trans, d); + if (rv.isOK()) { + trans.info().printf("Updated %s %s to %s", ur.user(), ur.role(), d.toString()); + } else { + trans.info().log(rv.errorString()); + } + } else { + return Result.err(Status.ERR_Denied, "You cannot change the key of this Data"); + } + } + return Result.err(Status.ERR_UserRoleNotFound,"No User Role with %s %s",ur.user(),ur.role()); + } + } + + public static interface Modify { + void change(UserRoleDAO.Data ur); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPrint.java new file mode 100644 index 00000000..12eb115a --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPrint.java @@ -0,0 +1,42 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.util.Chrono; + +public class URPrint implements Action { + private String info; + + public URPrint(String text) { + this.info = text; + } + + @Override + public Result exec(AuthzTrans trans, UserRole ur, String text) { + trans.info().log(info,text,ur.user(),"to",ur.role(),"expiring on",Chrono.dateOnlyStamp(ur.expires())); + return Result.ok(); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPunt.java new file mode 100644 index 00000000..18705fb8 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/actions/URPunt.java @@ -0,0 +1,70 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions; + +import java.io.IOException; +import java.util.Date; +import java.util.List; + +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.Cluster; + +public class URPunt extends ActionPuntDAO { + public URPunt(AuthzTrans trans, Cluster cluster, int months, int range, boolean dryRun) throws APIException, IOException { + super(trans,cluster, months, range,dryRun); + } + + public URPunt(AuthzTrans trans, ActionDAO adao, int months, int range) { + super(trans, adao, months, range); + } + + public Result exec(AuthzTrans trans, UserRole ur, String text) { + if (dryRun) { + trans.info().log("Would Update User",ur.user(),"and Role", ur.role(), text); + return Result.ok(); + } else { + Result> read = q.userRoleDAO.read(trans, ur.user(), ur.role()); + if (read.isOK()) { + for (UserRoleDAO.Data data : read.value) { + Date from = data.expires; + data.expires = puntDate(from); + if (data.expires.compareTo(from)<=0) { + trans.debug().printf("Error: %s is same or before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); + } else { + trans.info().log("Updating User",ur.user(),"and Role", ur.role(), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires), text); + q.userRoleDAO.update(trans, data); + } + } + return Result.ok(); + } else { + return Result.err(read); + } + } + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java new file mode 100644 index 00000000..fb3aefbe --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java @@ -0,0 +1,309 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TreeMap; +import java.util.UUID; + +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Approval implements CacheChange.Data { + public static final String RE_APPROVAL_IN_ROLE = "Re-Approval in Role '"; + public static final String RE_VALIDATE_ADMIN = "Re-Validate as Administrator for AAF Namespace '"; + public static final String RE_VALIDATE_OWNER = "Re-Validate Ownership for AAF Namespace '"; + + public static TreeMap> byApprover = new TreeMap<>(); + public static TreeMap> byUser = new TreeMap<>(); + public static TreeMap> byTicket = new TreeMap<>(); + private final static CacheChange cache = new CacheChange<>(); + + public final ApprovalDAO.Data add; + private String role; + + public Approval(UUID id, UUID ticket, String approver, Date last_notified, + String user, String memo, String operation, String status, String type, long updated) { + add = new ApprovalDAO.Data(); + add.id = id; + add.ticket = ticket; + add.approver = approver; + add.last_notified = last_notified; + add.user = user; + add.memo = memo; + add.operation = operation; + add.status = status; + add.type = type; + add.updated = new Date(updated); + role = roleFromMemo(memo); + } + + public static String roleFromMemo(String memo) { + if (memo==null) { + return null; + } + int first = memo.indexOf('\''); + if (first>=0) { + int second = memo.indexOf('\'', ++first); + if (second>=0) { + String role = memo.substring(first, second); + if (memo.startsWith(RE_VALIDATE_ADMIN)) { + return role + ".admin"; + } else if (memo.startsWith(RE_VALIDATE_OWNER)) { + return role + ".owner"; + } else if (memo.startsWith(RE_APPROVAL_IN_ROLE)) { + return role; + } + } + } + return null; + } + + public static void load(Trans trans, Session session, Creator creator ) { + trans.info().log( "query: " + creator.select() ); + TimeTaken tt = trans.start("Load Notify", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + tt = trans.start("Process Notify", Env.SUB); + + try { + List ln; + for (Row row : results.all()) { + ++count; + try { + Approval app = creator.create(row); + String person = app.getApprover(); + if (person!=null) { + ln = byApprover.get(person); + if (ln==null) { + ln = new ArrayList<>(); + byApprover.put(app.getApprover(), ln); + } + ln.add(app); + } + + + person = app.getUser(); + if (person!=null) { + ln = byUser.get(person); + if (ln==null) { + ln = new ArrayList<>(); + byUser.put(app.getUser(), ln); + } + ln.add(app); + } + UUID ticket = app.getTicket(); + if (ticket!=null) { + ln = byTicket.get(ticket); + if (ln==null) { + ln = new ArrayList<>(); + byTicket.put(app.getTicket(), ln); + } + ln.add(app); + } + } finally { + tt.done(); + } + } + } finally { + tt.done(); + trans.info().log("Found",count,"Approval Records"); + } + } + + @Override + public void expunge() { + List la = byApprover.get(getApprover()); + if (la!=null) { + la.remove(this); + } + + la = byUser.get(getUser()); + if (la!=null) { + la.remove(this); + } + UUID ticket = this.add==null?null:this.add.ticket; + if (ticket!=null) { + la = byTicket.get(this.add.ticket); + if (la!=null) { + la.remove(this); + } + } + } + + public void update(AuthzTrans trans, ApprovalDAO apprDAO, boolean dryRun) { + if (dryRun) { + trans.info().printf("Would update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); + } else { + trans.info().printf("Update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); + apprDAO.update(trans, add); + } + } + + public static Creator v2_0_17 = new Creator() { + @Override + public Approval create(Row row) { + return new Approval(row.getUUID(0), row.getUUID(1), row.getString(2), row.getTimestamp(3), + row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8) + ,row.getLong(9)/1000); + } + + @Override + public String select() { + return "select id,ticket,approver,last_notified,user,memo,operation,status,type,WRITETIME(status) from authz.approval"; + } + }; + + /** + * @return the lastNotified + */ + public Date getLast_notified() { + return add.last_notified; + } + /** + * @param lastNotified the lastNotified to set + */ + public void setLastNotified(Date last_notified) { + add.last_notified = last_notified; + } + /** + * @return the status + */ + public String getStatus() { + return add.status; + } + /** + * @param status the status to set + */ + public void setStatus(String status) { + add.status = status; + } + /** + * @return the id + */ + public UUID getId() { + return add.id; + } + /** + * @return the ticket + */ + public UUID getTicket() { + return add.ticket; + } + /** + * @return the approver + */ + public String getApprover() { + return add.approver; + } + /** + * @return the user + */ + public String getUser() { + return add.user; + } + /** + * @return the memo + */ + public String getMemo() { + return add.memo; + } + /** + * @return the operation + */ + public String getOperation() { + return add.operation; + } + /** + * @return the type + */ + public String getType() { + return add.type; + } + public void lapsed() { + add.ticket=null; + add.status="lapsed"; + } + + public String getRole() { + return role; + } + + public String toString() { + return getUser() + ' ' + getMemo(); + } + + public void delayDelete(AuthzTrans trans, ApprovalDAO ad, boolean dryRun, String text) { + if (dryRun) { + trans.info().log(text,"- Would Delete: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); + } else { + Result rv = ad.delete(trans, add, false); + if (rv.isOK()) { + trans.info().log(text,"- Deleted: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); + cache.delayedDelete(this); + } else { + trans.info().log(text,"- Failed to Delete Approval",getId()); + } + } + } + + + public static void resetLocalData() { + cache.resetLocalData(); + } + + public static int sizeForDeletion() { + return cache.cacheSize(); + } + + public static void delayDelete(AuthzTrans noAvg, ApprovalDAO apprDAO, boolean dryRun, List list, String text) { + if (list!=null) { + for (Approval a : list) { + a.delayDelete(noAvg, apprDAO, dryRun,text); + } + } + } + + public static boolean pendingDelete(Approval a) { + return cache.contains(a); + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approver.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approver.java new file mode 100644 index 00000000..6e27495f --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approver.java @@ -0,0 +1,62 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.HashMap; +import java.util.Map; + +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.org.Organization; + +public class Approver { + public String name; + public Organization org; + public Map userRequests; + + public Approver(String approver, Organization org) { + this.name = approver; + this.org = org; + userRequests = new HashMap<>(); + } + + public void addRequest(String user) { + if (userRequests.get(user) == null) { + userRequests.put(user, 1); + } else { + Integer curCount = userRequests.remove(user); + userRequests.put(user, curCount+1); + } + } + + /** + * @param sb + * @return + */ + public void build(Message msg) { + msg.clear(); + msg.line("You have %d total pending approvals from the following users:", userRequests.size()); + for (Map.Entry entry : userRequests.entrySet()) { + msg.line(" %s (%d)",entry.getKey(),entry.getValue()); + } + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java new file mode 100644 index 00000000..5df5dcdc --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java @@ -0,0 +1,71 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.aaf.auth.batch.helpers; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; + +public class CQLBatch { + private Session session; + private StringBuilder sb; + private int hasAdded; + + public CQLBatch(Session session) { + this.session = session; + sb = new StringBuilder(); + hasAdded = 0; + } + public StringBuilder begin() { + sb.setLength(0); + sb.append("BEGIN BATCH\n"); + hasAdded = sb.length(); + return sb; + } + + private boolean end() { + if(sb.length()==hasAdded) { + System.out.println("Nothing to Process"); + return false; + } else { + sb.append("APPLY BATCH;\n"); + System.out.println(sb); + return true; + } + } + + public ResultSet execute() { + if(end()) { + return session.execute(sb.toString()); + } else { + return null; + } + } + + public ResultSet execute(boolean dryRun) { + if(dryRun) { + end(); + return null; + } else { + return execute(); + } + + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CacheChange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CacheChange.java new file mode 100644 index 00000000..a4cfcbec --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CacheChange.java @@ -0,0 +1,63 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.List; + +public class CacheChange { + private List removed; + + public CacheChange() { + removed = new ArrayList<>(); + } + + interface Data { + public abstract void expunge(); + } + + public final void delayedDelete(T t) { + removed.add(t); + } + + public final List getRemoved() { + return removed; + } + + public final void resetLocalData() { + if (removed==null || removed.isEmpty()) { + return; + } + for (T t : removed) { + t.expunge(); + } + removed.clear(); + } + + public int cacheSize() { + return removed.size(); + } + + public boolean contains(T t) { + return removed.contains(t); + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java new file mode 100644 index 00000000..152c6331 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java @@ -0,0 +1,41 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import com.datastax.driver.core.Row; + +public abstract class Creator { + public abstract T create(Row row); + public abstract String select(); + + public String query(String where) { + StringBuilder sb = new StringBuilder(select()); + if (where!=null) { + sb.append(" WHERE "); + sb.append(where); + } + sb.append(';'); + return sb.toString(); + } + + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java new file mode 100644 index 00000000..979cdf0b --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java @@ -0,0 +1,325 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeMap; + +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Cred { + public static final TreeMap data = new TreeMap<>(); + public static final TreeMap> byNS = new TreeMap<>(); + + public final String id; + public final List instances; + public final String ns; + + public Cred(String id) { + this.id = id; + instances = new ArrayList<>(); + ns=Question.domain2ns(id); + } + + public static class Instance { + public final int type; + public final Date expires,written; + public final Integer other; + + public Instance(int type, Date expires, Integer other, long written) { + this.type = type; + this.expires = expires; + this.other = other; + this.written = new Date(written); + } + + public String toString() { + return expires.toString() + ": " + type; + } + } + + public Date last(final int ... types) { + Date last = null; + for (Instance i : instances) { + if (types.length>0) { // filter by types, if requested + boolean quit = true; + for (int t : types) { + if (t==i.type) { + quit=false; + break; + } + } + if (quit) { + continue; + } + } + if (last==null || i.expires.after(last)) { + last = i.expires; + } + } + return last; + } + + + public Set types() { + Set types = new HashSet<>(); + for (Instance i : instances) { + types.add(i.type); + } + return types; + } + + public static void load(Trans trans, Session session, int ... types ) { + load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred;",types); + + } + + public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) { + load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred WHERE ns='" + ns + "';"); + } + + private static void load(Trans trans, Session session, String query, int ...types) { + + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read Creds", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load Credentials", Env.SUB); + try { + while (iter.hasNext()) { + ++count; + row = iter.next(); + int type = row.getInt(1); + if (types.length>0) { // filter by types, if requested + boolean quit = true; + for (int t : types) { + if (t==type) { + break; + } + } + if (quit) { + continue; + } + } + add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4)); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",count,"creds"); + } + } + + public static void add( + final String id, + final int type, + final Date timestamp, + final int other, + final long written + ) { + Cred cred = data.get(id); + if (cred==null) { + cred = new Cred(id); + data.put(id, cred); + } + cred.instances.add(new Instance(type, timestamp, other, written/1000)); + + List lscd = byNS.get(cred.ns); + if (lscd==null) { + byNS.put(cred.ns, (lscd=new ArrayList<>())); + } + boolean found = false; + for (Cred c : lscd) { + if (c.id.equals(cred.id)) { + found=true; + break; + } + } + if (!found) { + lscd.add(cred); + } + } + + + /** + * Count entries in Cred data. + * Note, as opposed to other methods, need to load the whole cred table for the Types. + * @param numbuckets + * @return + */ + public static CredCount count(int numbuckets) { + CredCount cc = new CredCount(numbuckets); + for (Cred c : data.values()) { + for (Instance ci : c.instances) { + cc.inc(ci.type,ci.written, ci.expires); + } + } + return cc; + } + + public static class CredCount { + public int raw[]; + public int basic_auth[]; + public int basic_auth_256[]; + public int cert[]; + public int x509Added[]; + public int x509Expired[]; + public Date dates[]; + + public CredCount(int numbuckets) { + raw = new int[numbuckets]; + basic_auth = new int[numbuckets]; + basic_auth_256 = new int[numbuckets]; + cert = new int[numbuckets]; + x509Added = new int[numbuckets]; + x509Expired = new int[numbuckets]; + dates = new Date[numbuckets]; + GregorianCalendar gc = new GregorianCalendar(); + dates[0]=gc.getTime(); // now + gc.set(GregorianCalendar.DAY_OF_MONTH, 1); + gc.set(GregorianCalendar.HOUR, 0); + gc.set(GregorianCalendar.MINUTE, 0); + gc.set(GregorianCalendar.SECOND,0); + gc.set(GregorianCalendar.MILLISECOND,0); + gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month + for (int i=1;i row) { + sb.append("DELETE from authz.cred WHERE id='"); + sb.append(row.get(1)); + sb.append("' AND type="); + sb.append(Integer.parseInt(row.get(3))); + // Note: We have to work with long, because Expires is part of Key... can't easily do date. + sb.append(" AND expires=dateof(maxtimeuuid("); + sb.append(row.get(5)); + sb.append("));\n"); + } + + + public String toString() { + StringBuilder sb = new StringBuilder(id); + sb.append('['); + for (Instance i : instances) { + sb.append('{'); + sb.append(i.type); + sb.append(",\""); + sb.append(i.expires); + sb.append("\"}"); + } + sb.append(']'); + return sb.toString(); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return id.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return id.equals(obj); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java new file mode 100644 index 00000000..f6a25e7f --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java @@ -0,0 +1,178 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.onap.aaf.cadi.Access; + +public class ExpireRange { + private static final String AAF_BATCH_RANGE = "aaf_batch_range."; + public Map> ranges; + public final Date now; + + public ExpireRange(final Access access) { + now = new Date(); + ranges = new HashMap<>(); + int i=0; + String prop = access.getProperty(AAF_BATCH_RANGE + i,null); + if(prop==null) { + if(i==0) { + List lcred = getRangeList("cred"); + List lur = getRangeList("ur"); + List lx509 = getRangeList("x509"); + + Range del = new Range("Delete",0,0,-1,0,GregorianCalendar.WEEK_OF_MONTH,-2); + lur.add(del); + lcred.add(del); + lx509.add(del); + + lcred.add(new Range("CredOneWeek",3,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); + lcred.add(new Range("CredTwoWeek",2,1,GregorianCalendar.WEEK_OF_MONTH,1,GregorianCalendar.WEEK_OF_MONTH,2)); + lcred.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + lcred.add(new Range("TwoMonth",1,0,GregorianCalendar.MONTH,1,GregorianCalendar.MONTH,2)); + + lur.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + + lx509.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + } + } + } + + public Set names() { + Set names = new HashSet<>(); + for(List lr : ranges.values()) { + for(Range r : lr) { + names.add(r.name); + } + } + + return names; + } + + private synchronized List getRangeList(final String key) { + List rv = ranges.get(key); + if(rv==null) { + rv = new ArrayList<>(); + ranges.put(key, rv); + } + return rv; + } + + public class Range { + private final String name; + private final int reportingLevel; + private final int interval; // in Days + private final Date start; + private final Date end; + + public Range( + final String name, final int reportingLevel, final int interval, + final int startGCType, final int startQty, + final int endGCType,final int endQty) { + this.name = name; + this.reportingLevel = reportingLevel; + this.interval = interval; + GregorianCalendar gc = new GregorianCalendar(); + if(startGCType<0) { + gc.set(GregorianCalendar.YEAR, 1); + } else { + gc.setTime(now); + gc.add(startGCType, startQty); + } + start = gc.getTime(); + + if(endGCType<0) { + gc.set(GregorianCalendar.YEAR, 1); + } else { + gc.setTime(now); + gc.add(endGCType, endQty); + } + end = gc.getTime(); + } + + public String name() { + return name; + } + + public int reportingLevel() { + return reportingLevel; + } + + public Date getStart() { + return start; + } + + public Date getEnd() { + return end; + } + + private boolean inRange(final Date date) { + if(date==null) { + return false; + } else { + return date.getTime()>=start.getTime() && date.before(end); + } + } + + public boolean shouldContact(final Date lastContact) { + if(reportingLevel<=0) { + return false; + } else if(lastContact==null) { + return true; + } else if(interval==0) { + return lastContact.before(start); + } else { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(now); + gc.add(GregorianCalendar.DAY_OF_WEEK, interval); + return lastContact.before(gc.getTime()); + } + } + } + + public Range getRange(final String key, final Date date) { + Range rv = null; + if(date!=null) { + List lr = ranges.get(key); + if(lr==null) { + return null; + } else { + for(Range r : lr) { + if(r.inRange(date)) { + rv = r; + break; + } + } + } + } + return rv; + } + + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java new file mode 100644 index 00000000..ac4a1323 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java @@ -0,0 +1,203 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; + +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Future implements CacheChange.Data, Comparable { + public static final Map data = new TreeMap<>(); + public static final Map> byRole = new TreeMap<>(); + + public final FutureDAO.Data fdd; + public final String role; // derived + private static final CacheChange cache = new CacheChange<>(); + + + public final UUID id() { + return fdd.id; + } + + public final String memo() { + return fdd.memo; + } + + public final String target() { + return fdd.target; + } + + public final Date start() { + return fdd.start; + } + + public final Date expires() { + return fdd.expires; + } + + + public Future(UUID id, String memo, String target, Date start, Date expires, ByteBuffer construct) { + fdd = new FutureDAO.Data(); + fdd.id = id; + fdd.memo = memo; + fdd.target = target; + fdd.start = start; + fdd.expires = expires; + fdd.construct = construct; + role = Approval.roleFromMemo(memo); + } + + public static void load(Trans trans, Session session, Creator creator) { + trans.info().log( "query: " + creator.select() ); + ResultSet results; + TimeTaken tt = trans.start("Load Futures", Env.REMOTE); + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); + } finally { + tt.done(); + } + + int count = 0; + tt = trans.start("Process Futures", Env.SUB); + try { + for (Row row : results.all()) { + ++count; + Future f = creator.create(row); + data.put(f.fdd.id,f); + if (f.role==null) { + continue; + } + List lf = byRole.get(f.role); + if (lf==null) { + lf = new ArrayList<>(); + byRole.put(f.role,lf); + } + lf.add(f); + + } + } finally { + tt.done(); + trans.info().log("Found",count,"Futures"); + } + } + + public static Creator v2_0_17 = new Creator() { + @Override + public Future create(Row row) { + return new Future(row.getUUID(0),row.getString(1),row.getString(2), + row.getTimestamp(3),row.getTimestamp(4), null); + } + + @Override + public String select() { + return "select id,memo,target,start,expires from authz.future"; + } + }; + + public static Creator withConstruct = new Creator() { + @Override + public String select() { + return "select id,memo,target,start,expires,construct from authz.future"; + } + + @Override + public Future create(Row row) { + return new Future(row.getUUID(0),row.getString(1),row.getString(2), + row.getTimestamp(3),row.getTimestamp(4), row.getBytes(5)); + } + + }; + + public Result delayedDelete(AuthzTrans trans, FutureDAO fd, boolean dryRun, String text) { + Result rv; + if (dryRun) { + trans.info().log(text,"- Would Delete: ",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); + rv = Result.ok(); + } else { + rv = fd.delete(trans, fdd, true); // need to read for undelete + if (rv.isOK()) { + trans.info().log(text, "- Deleted:",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); + cache.delayedDelete(this); + } else { + if (rv.status!=6) { + trans.info().log(text,"- Failed to Delete Future", fdd.id); + } + } + } + return rv; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.helpers.CacheChange.Data#resetLocalData() + */ + @Override + public void expunge() { + data.remove(fdd.id); + if (role!=null) { + List lf = byRole.get(role); + if (lf!=null) { + lf.remove(this); + } + } + } + + @Override + public int compareTo(Future o) { + if (o==null) { + return -1; + } + return fdd.id.compareTo(o.fdd.id); + } + + public static void resetLocalData() { + cache.resetLocalData(); + } + + public static int sizeForDeletion() { + return cache.cacheSize(); + } + + public static boolean pendingDelete(Future f) { + return cache.contains(f); + } + + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/History.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/History.java new file mode 100644 index 00000000..a172738c --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/History.java @@ -0,0 +1,178 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.nio.ByteBuffer; +import java.util.Iterator; +import java.util.UUID; + +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class History { + public final UUID id; + public final String action; + public final String memo; + public final String reconstruct; + public final String subject; + public final String target; + public final String user; + public final int yr_mon; + + public History(UUID id, String action, String memo, String subject, String target, String user, int yr_mon) { + this.id = id; + this.action = action; + this.memo = memo; + this.reconstruct = null; + this.subject = subject; + this.target = target; + this.user = user; + this.yr_mon = yr_mon; + } + + public History(UUID id, String action, String memo, String reconstruct, String subject, String target, String user, int yr_mon) { + this.id = id; + this.action = action; + this.memo = memo; + this.reconstruct = reconstruct; + this.subject = subject; + this.target = target; + this.user = user; + this.yr_mon = yr_mon; + } + + public static void load(Trans trans, Session session, Creator creator, Loader loader) { + trans.info().log( "query: " + creator.select() ); + TimeTaken tt = trans.start("Read History", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( creator.select() ).setReadTimeoutMillis(240000); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load History", Env.SUB); + try { + while (iter.hasNext()) { + ++count; + row = iter.next(); + loader.exec(creator.create(row)); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",count,"histories"); + } + } + + public String toString() { + return String.format("%s %d %s, %s, %s, %s, %s", + id.toString(), + yr_mon, + user, + target, + action, + subject, + memo); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return id.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return id.equals(obj); + } + + public static Creator sansConstruct = new Creator () { + @Override + public History create(Row row) { + return new History( + row.getUUID(0), + row.getString(1), + row.getString(2), + row.getString(3), + row.getString(4), + row.getString(5), + row.getInt(6)); + } + + @Override + public String select() { + return "SELECT id, action, memo, subject, target, user, yr_mon from authz.history LIMIT 10000000 "; + } + }; + + public static Creator avecConstruct = new Creator () { + private final StringBuilder sb = new StringBuilder(); + + @Override + public History create(Row row) { + ByteBuffer bb = row.getBytes(3); + sb.setLength(0); + + if (bb!=null && bb.hasRemaining()) { + sb.append("0x"); + while (bb.hasRemaining()) { + sb.append(String.format("%02x",bb.get())); + } + bb.flip(); + } + return new History( + row.getUUID(0), + row.getString(1), + row.getString(2), + sb.toString(), + row.getString(4), + row.getString(5), + row.getString(6), + row.getInt(7)); + } + + @Override + public String select() { + return "SELECT id, action, memo, reconstruct, subject, target, user, yr_mon from authz.history LIMIT 10000000 "; + } + }; + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/InputIterator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/InputIterator.java new file mode 100644 index 00000000..04d9a019 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/InputIterator.java @@ -0,0 +1,73 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Iterator; +import java.util.NoSuchElementException; + +public class InputIterator implements Iterable { + private BufferedReader in; + private final PrintStream out; + private final String prompt, instructions; + + public InputIterator(BufferedReader in, PrintStream out, String prompt, String instructions) { + this.in = in; + this.out = out; + this.prompt = prompt; + this.instructions = instructions; + } + + @Override + public Iterator iterator() { + out.println(instructions); + return new Iterator() { + String input; + @Override + public boolean hasNext() { + out.append(prompt); + try { + input = in.readLine(); + } catch (IOException e) { + input = null; + return false; + } + return input.length()>0; + } + + @Override + public String next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return input; + } + + @Override + public void remove() { + } + }; + } +} + diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Loader.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Loader.java new file mode 100644 index 00000000..ea533b8b --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Loader.java @@ -0,0 +1,26 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +public interface Loader { + public void exec(T t); +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MiscID.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MiscID.java new file mode 100644 index 00000000..45875a20 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MiscID.java @@ -0,0 +1,188 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.Map; +import java.util.TreeMap; + +import org.onap.aaf.auth.batch.BatchException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class MiscID { + public static final TreeMap data = new TreeMap<>(); + /* + Sample Record + aad890|mj9030|20040902|20120207 + + **** Field Definitions **** + MISCID - AT&T Miscellaneous ID - Non-User ID (Types: Internal Mechanized ID, External Mechanized ID, Datagate ID, Customer ID, Vendor ID, Exchange Mail ID, CLEC ID, Specialized ID, Training ID) + SPONSOR_ATTUID - ATTUID of MiscID Sponsor (Owner) + CREATE_DATE - Date when MiscID was created + LAST_RENEWAL_DATE - Date when MiscID Sponsorship was last renewed + */ + public String id,sponsor,created,renewal; + + private static final String fieldString = "id,created,sponsor,renewal"; + + /** + * Load a Row of Strings (from CSV file). + * + * Be CAREFUL that the Row lists match the Fields above!!! If this changes, change + * 1) This Object + * 2) DB "suits.cql" + * 3) Alter existing Tables + * @param row + * @throws BatchException + * @throws IllegalAccessException + * @throws IllegalArgumentException + */ + public void set(String row []) throws BatchException { + if (row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} + id = row[0]; + sponsor = row[1]; + created = row[2]; + renewal = row[3]; + } + + public void set(Row row) { + id = row.getString(0); + sponsor = row.getString(1); + created = row.getString(2); + renewal = row.getString(3); + } + + + public static void load(Trans trans, Session session ) { + load(trans, session,"SELECT " + fieldString + " FROM authz.miscid;",data); + } + + public static void load(Trans trans, Session session, Map map ) { + load(trans, session,"SELECT " + fieldString + " FROM authz.miscid;",map); + } + + public static void loadOne(Trans trans, Session session, String id ) { + load(trans, session,"SELECT " + fieldString + " FROM authz.miscid WHERE id ='" + id + "';", data); + } + + public static void load(Trans trans, Session session, String query, Map map) { + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read MiscID", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + try { + tt = trans.start("Load Map", Env.SUB); + try { + for ( Row row : results.all()) { + MiscID miscID = new MiscID(); + miscID.set(row); + data.put(miscID.id,miscID); + ++count; + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",count,"miscID records"); + } + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return id.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj!=null && obj instanceof MiscID) { + return id.equals(((MiscID)obj).id); + } + return false; + } + + public StringBuilder insertStmt() throws IllegalArgumentException, IllegalAccessException { + StringBuilder sb = new StringBuilder("INSERT INTO authz.miscid ("); + sb.append(fieldString); + sb.append(") VALUES ('"); + sb.append(id); + sb.append("','"); + sb.append(sponsor); + sb.append("','"); + sb.append(created); + sb.append("','"); + sb.append(renewal); + sb.append("')"); + return sb; + } + + public StringBuilder updateStmt(MiscID source) { + StringBuilder sb = null; + if (id.equals(source.id)) { + sb = addField(sb,"sponser",sponsor,source.sponsor); + sb = addField(sb,"created",created,source.created); + sb = addField(sb,"renewal",renewal,source.renewal); + } + if (sb!=null) { + sb.append(" WHERE id='"); + sb.append(id); + sb.append('\''); + } + return sb; + } + + private StringBuilder addField(StringBuilder sb, String name, String a, String b) { + if (!a.equals(b)) { + if (sb==null) { + sb = new StringBuilder("UPDATE authz.miscid SET "); + } else { + sb.append(','); + } + sb.append(name); + sb.append("='"); + sb.append(b); + sb.append('\''); + } + return sb; + } + + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MonthData.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MonthData.java new file mode 100644 index 00000000..35ad6a10 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/MonthData.java @@ -0,0 +1,120 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintStream; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; + +import org.onap.aaf.misc.env.util.Split; + +import java.util.Set; +import java.util.TreeMap; + +public class MonthData { + public final Map> data = new TreeMap<>(); + private File f; + + public MonthData(String env) throws IOException { + f = new File("Monthly"+env+".dat"); + + if (f.exists()) { + BufferedReader br = new BufferedReader(new FileReader(f)); + try { + String line; + String[] split; + while ((line=br.readLine())!=null) { + if (!line.startsWith("#")) { + split = Split.split(',', line); + if (split.length==5) { + add(Integer.parseInt(split[0]),split[1], + Integer.parseInt(split[2]), + Integer.parseInt(split[3]), + Integer.parseInt(split[4]) + ); + } + } + } + } finally { + br.close(); + } + } + } + + public void add(int yr_mon, String target, long total, long adds, long drops) { + Set row = data.get(yr_mon); + if (row==null) { + data.put(yr_mon, (row=new HashSet<>())); + } + row.add(new Row(target,total,adds,drops)); + } + + public boolean notExists(int yr_mon) { + return data.get(yr_mon)==null; + } + + public static class Row implements Comparable { + public final String target; + public final long total; + public final long adds; + public final long drops; + + public Row(String t, long it, long a, long d) { + target = t; + total = it; + adds = a; + drops = d; + } + + @Override + public int compareTo(Row o) { + return target.compareTo(o.target); + } + + public String toString() { + return target + '|' + total + '|' + drops + '|' + adds; + } + } + + public void write() throws IOException { + if (f.exists()) { + File bu = new File(f.getName()+".bak"); + f.renameTo(bu); + } + PrintStream ps = new PrintStream(f); + try { + for ( Entry> rows : data.entrySet()) { + for (Row row : rows.getValue()) { + ps.printf("%d,%s,%d,%d,%d\n",rows.getKey(),row.target,row.total,row.adds,row.drops); + } + } + } finally { + ps.close(); + } + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java new file mode 100644 index 00000000..3df72e12 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java @@ -0,0 +1,168 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class NS implements Comparable { + public final static Map data = new TreeMap<>(); + + public final String name, description, parent; + public final int scope,type; + + public NS(String name, String description, String parent, int type, int scope) { + this.name = name; + this.description = description; + this.parent = parent; + this.scope = scope; + this.type = type; + } + + public static void load(Trans trans, Session session, Creator creator) { + load(trans,session, + "select name, description, parent, type, scope from authz.ns;" + ,creator); + } + + public static void loadOne(Trans trans, Session session, Creator creator, String ns) { + load(trans,session, + ("select name, description, parent, type, scope from authz.ns WHERE name='"+ns+"';") + ,creator + ); + } + + private static void load(Trans trans, Session session, String query, Creator creator) { + trans.info().log( "query: " + query ); + ResultSet results; + TimeTaken tt; + + tt = trans.start("Read Namespaces", Env.REMOTE); + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + + + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load Namespaces", Env.SUB); + try { + while (iter.hasNext()) { + row = iter.next(); + NS ns = creator.create(row); + data.put(ns.name,ns); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",data.size(),"Namespaces"); + } + + } + + public static long count(Trans trans, Session session) { + String query = "select count(*) from authz.ns LIMIT 1000000;"; + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); + } finally { + tt.done(); + } + } + + public String toString() { + return name; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return name.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return name.equals(obj); + } + + @Override + public int compareTo(NS o) { + return name.compareTo(o.name); + } + + public static class NSSplit { + public String ns; + public String other; + public NSSplit(String s, int dot) { + ns = s.substring(0,dot); + other = s.substring(dot+1); + } + } + public static NSSplit deriveParent(String dotted) { + if (dotted==null)return null; + for (int idx = dotted.lastIndexOf('.');idx>=0; idx=dotted.lastIndexOf('.',idx-1)) { + if (data.get(dotted.substring(0, idx))!=null) { + return new NSSplit(dotted,idx); + } + } + return null; + } + + public static Creator v2_0_11 = new Creator () { + @Override + public NS create(Row row) { + return new NS(row.getString(0),row.getString(1), row.getString(2),row.getInt(3),row.getInt(4)); + } + + @Override + public String select() { + return "SELECT name, description, parent, type, scope FROM authz.ns "; + } + }; + + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Notification.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Notification.java new file mode 100644 index 00000000..5c7a8269 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Notification.java @@ -0,0 +1,209 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TreeMap; + +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Notification { + public enum TYPE { + OA("Owner Approval",1),SA("Supervisor Approval",2),CN("Credential Expiration",20); + + private String desc; + private int type; + + private TYPE(String desc,int type) { + this.desc = desc; + this.type = type; + } + + public String desc() { + return desc; + } + + public int idx() { + return type; + } + + public static TYPE get(int idx) { + for (TYPE nt : TYPE.values()) { + if (idx==nt.type) { + return nt; + } + } + return null; + } + } + + + public static final TreeMap> data = new TreeMap<>(); + public static final Date now = new Date(); + + public final String user; + public final TYPE type; + public Date last; + public int checksum; + public Message msg; + private int current; + public Organization org; + public int count; + + private Notification(String user, TYPE nt, Date last, int checksum) { + this.user = user; + this.type = nt; + this.last = last; + this.checksum = checksum; + current = 0; + count = 0; + } + + public static void load(Trans trans, Session session, Creator creator ) { + trans.info().log( "query: " + creator.select() ); + TimeTaken tt = trans.start("Load Notify", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + tt = trans.start("Process Notify", Env.SUB); + + try { + for (Row row : results.all()) { + ++count; + try { + Notification not = creator.create(row); + List ln = data.get(not.user); + if (ln==null) { + ln = new ArrayList<>(); + data.put(not.user, ln); + } + ln.add(not); + } finally { + tt.done(); + } + } + } finally { + tt.done(); + trans.info().log("Found",count,"Notify Records"); + } + } + + public static Notification get(String user, TYPE type) { + List ln = data.get(user); + if (ln!=null) { + for (Notification n : ln) { + if (type.equals(n.type)) { + return n; + } + } + } + return null; + } + + public static Notification create(String user, TYPE type) { + return new Notification(user,type,null,0); + } + + public static Creator v2_0_18 = new Creator() { + @Override + public Notification create(Row row) { + int idx =row.getInt(1); + TYPE type = TYPE.get(idx); + if (type==null) { + return null; + } + return new Notification(row.getString(0), type, row.getTimestamp(2), row.getInt(3)); + } + + @Override + public String select() { + return "SELECT user,type,last,checksum FROM authz.notify LIMIT 100000"; + } + }; + + + public void set(Message msg) { + this.msg = msg; + } + + public int checksum() { + if (msg==null) { + current=0; + } else if (current==0) { + for (String l : msg.lines) { + for (byte b : l.getBytes()) { + current+=b; + } + } + } + return current; + } + + public boolean update(AuthzTrans trans, Session session, boolean dryRun) { + checksum(); + if (last==null || current==0 || current!=checksum) { + last = now; + current = checksum(); + String update = "UPDATE authz.notify SET " + + "last = '" + Chrono.utcStamp(last) + + "', checksum=" + + current + + " WHERE user='" + + user + + "' AND type=" + + type.idx() + + ";"; + if (dryRun) { + trans.info().log("Would",update); + } else { + session.execute(update); + } + return true; + } + return false; + } + + public String toString() { + return "\"" + user + "\",\"" + type.name() + "\",\"" + + Chrono.dateTime(last)+ "\", " + checksum; + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NsAttrib.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NsAttrib.java new file mode 100644 index 00000000..c8419d50 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NsAttrib.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class NsAttrib { + public static final List data = new ArrayList<>(); + public static final SortedMap> byKey = new TreeMap<>(); + public static final SortedMap> byNS = new TreeMap<>(); + + public final String ns; + public final String key; + public final String value; + public static Creator v2_0_11 = new Creator() { + @Override + public NsAttrib create(Row row) { + return new NsAttrib(row.getString(0), row.getString(1), row.getString(2)); + } + + @Override + public String select() { + return "select ns,key,value from authz.ns_attrib"; + } + }; + + public NsAttrib(String ns, String key, String value) { + this.ns = ns; + this.key = key; + this.value = value; + } + + public static void load(Trans trans, Session session, Creator creator ) { + trans.info().log( "query: " + creator.select() ); + ResultSet results; + TimeTaken tt = trans.start("Load NsAttributes", Env.REMOTE); + try { + Statement stmt = new SimpleStatement(creator.select()); + results = session.execute(stmt); + } finally { + tt.done(); + } + int count = 0; + tt = trans.start("Process NsAttributes", Env.SUB); + + try { + for (Row row : results.all()) { + ++count; + NsAttrib ur = creator.create(row); + data.add(ur); + + List lna = byKey.get(ur.key); + if (lna==null) { + lna = new ArrayList<>(); + byKey.put(ur.key, lna); + } + lna.add(ur); + + lna = byNS.get(ur.ns); + if (lna==null) { + lna = new ArrayList<>(); + byNS.put(ur.ns, lna); + } + lna.add(ur); + } + } finally { + tt.done(); + trans.info().log("Found",count,"NS Attributes"); + } + } + + public String toString() { + return '"' + ns + "\",\"" + key + "\",\"" + value +'"'; + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Perm.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Perm.java new file mode 100644 index 00000000..21bd71ee --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Perm.java @@ -0,0 +1,174 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeMap; + +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Perm implements Comparable { + public static final TreeMap> data = new TreeMap<>(); + public static final TreeMap keys = new TreeMap<>(); + private static List deletePerms = new ArrayList<>(); + + public final String ns, type, instance, action,description; + private String fullType = null, fullPerm = null, encode = null; + public final Set roles; + + public String encode() { + if (encode == null) { + encode = ns + '|' + type + '|' + instance + '|' + action; + } + return encode; + } + + public String fullType() { + if (fullType==null) { + fullType = ns + '.' + type; + } + return fullType; + } + + public String fullPerm() { + if (fullPerm==null) { + fullPerm = ns + '.' + type + '|' + instance + '|' + action; + } + return fullPerm; + } + + public Perm(String ns, String type, String instance, String action, String description, Set roles) { + this.ns = ns; + this.type = type; + this.instance = instance; + this.action = action; + this.description = description; + // 2.0.11 +// this.full = encode();//ns+'.'+type+'|'+instance+'|'+action; + this.roles = roles; + } + + public static void load(Trans trans, Session session) { + load(trans, session, "select ns, type, instance, action, description, roles from authz.perm;"); + } + + public static void loadOneNS(Trans trans, Session session, String ns) { + load(trans, session, "select ns, type, instance, action, description, roles from authz.perm WHERE ns='" + ns + "';"); + + } + + private static void load(Trans trans, Session session, String query) { + // + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read Perms", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load Perms", Env.SUB); + try { + while (iter.hasNext()) { + row = iter.next(); + Perm pk = new Perm( + row.getString(0),row.getString(1),row.getString(2), + row.getString(3), row.getString(4), row.getSet(5,String.class)); + keys.put(pk.encode(), pk); + data.put(pk,pk.roles); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",data.size(),"perms"); + } + } + + public static long count(Trans trans, Session session) { + String query = "select count(*) from authz.perm LIMIT 1000000;"; + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); + } finally { + tt.done(); + } + } + + public String toString() { + return encode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return encode().hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return encode().equals(obj); + } + + @Override + public int compareTo(Perm o) { + return encode().compareTo(o.encode()); + } + + public static void stageRemove(Perm p) { + deletePerms.add(p); + } + + public static void executeRemove() { + for (Perm p : deletePerms) { + keys.remove(p.encode); + data.remove(p); + } + deletePerms.clear(); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java new file mode 100644 index 00000000..4b4a2551 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java @@ -0,0 +1,175 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TreeMap; + +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class Role implements Comparable { + public static final TreeMap> data = new TreeMap<>(); + public static final TreeMap keys = new TreeMap<>(); + public static final TreeMap byName = new TreeMap<>(); + private static List deleteRoles = new ArrayList<>(); + + public final String ns, name, description; + private String full, encode; + public final Set perms; + + public Role(String full) { + ns = name = description = ""; + this.full = full; + perms = new HashSet<>(); + } + + public Role(String ns, String name, String description,Set perms) { + this.ns = ns; + this.name = name; + this.description = description; + this.full = null; + this.encode = null; + this.perms = perms; + } + + public String encode() { + if (encode==null) { + encode = ns + '|' + name; + } + return encode; + } + + public String fullName() { + if (full==null) { + full = ns + '.' + name; + } + return full; + } + + public static void load(Trans trans, Session session ) { + load(trans,session,"select ns, name, description, perms from authz.role;"); + } + + public static void loadOneNS(Trans trans, Session session, String ns ) { + load(trans,session,"select ns, name, description, perms from authz.role WHERE ns='" + ns + "';"); + } + + private static void load(Trans trans, Session session, String query) { + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read Roles", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load Roles", Env.SUB); + try { + while (iter.hasNext()) { + row = iter.next(); + Role rk =new Role(row.getString(0),row.getString(1), row.getString(2),row.getSet(3,String.class)); + keys.put(rk.encode(), rk); + data.put(rk,rk.perms); + byName.put(rk.fullName(), rk); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",data.size(),"roles"); + } + } + + public static long count(Trans trans, Session session) { + String query = "select count(*) from authz.role LIMIT 1000000;"; + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); + } finally { + tt.done(); + } + } + + public String toString() { + return encode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return encode().hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return encode().equals(obj); + } + + @Override + public int compareTo(Role o) { + return encode().compareTo(o.encode()); + } + + public static String fullName(String role) { + return role.replace('|', '.'); + } + + public static void stageRemove(Role r) { + deleteRoles.add(r); + } + + public static void executeRemove() { + for (Role p : deleteRoles) { + keys.remove(p.encode); + data.remove(p); + } + deleteRoles.clear(); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java new file mode 100644 index 00000000..30069d64 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java @@ -0,0 +1,326 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.onap.aaf.auth.batch.actions.URDelete; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class UserRole implements Cloneable, CacheChange.Data { + + private static final String SEPARATOR = "\",\""; + + // CACHE Calling + private static final String LOG_FMT = "%s UserRole - %s: %s-%s (%s, %s) expiring %s"; + private static final String REPLAY_FMT = "%s|%s|%s|%s|%s\n"; + private static final String DELETE_FMT = "# %s\n"+ REPLAY_FMT; + + private static final List data = new ArrayList<>(); + private static final SortedMap> byUser = new TreeMap<>(); + private static final SortedMap> byRole = new TreeMap<>(); + private static final CacheChange cache = new CacheChange<>(); + private static PrintStream urDelete = System.out; + private static PrintStream urRecover = System.err; + private static int totalLoaded; + private int deleted; + private Data urdd; + + public static final Creator v2_0_11 = new Creator() { + @Override + public UserRole create(Row row) { + return new UserRole(row.getString(0), row.getString(1), row.getString(2),row.getString(3),row.getTimestamp(4)); + } + + @Override + public String select() { + return "select user,role,ns,rname,expires from authz.user_role"; + } + }; + + public UserRole(String user, String ns, String rname, Date expires) { + urdd = new UserRoleDAO.Data(); + urdd.user = user; + urdd.role = ns + '.' + rname; + urdd.ns = ns; + urdd.rname = rname; + urdd.expires = expires; + } + + public UserRole(String user, String role, String ns, String rname, Date expires) { + urdd = new UserRoleDAO.Data(); + urdd.user = user; + urdd.role = role; + urdd.ns = ns; + urdd.rname = rname; + urdd.expires = expires; + } + + public static List getData() { + return data; + } + + public static SortedMap> getByUser() { + return byUser; + } + + public static SortedMap> getByRole() { + return byRole; + } + + public static void load(Trans trans, Session session, Creator creator) { + load(trans,session,creator,null,new DataLoadVisitor()); + } + + public static void load(Trans trans, Session session, Creator creator, Visitor visitor ) { + load(trans,session,creator,null,visitor); + } + + public static void loadOneRole(Trans trans, Session session, Creator creator, String role, Visitor visitor) { + load(trans,session,creator,"role='" + role +"' ALLOW FILTERING;",visitor); + } + + public static void loadOneUser(Trans trans, Session session, Creator creator, String user, Visitor visitor ) { + load(trans,session,creator,"role='"+ user +"';",visitor); + } + + private static void load(Trans trans, Session session, Creator creator, String where, Visitor visitor) { + String query = creator.query(where); + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read UserRoles", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + try { + tt = trans.start("Load UserRole", Env.SUB); + try { + iterateResults(creator, results.iterator(), visitor); + } finally { + tt.done(); + } + } finally { + trans.info().log("Loaded",totalLoaded,"UserRoles"); + } + } + + private static void iterateResults(Creator creator, Iterator iter, Visitor visit ) { + Row row; + while (iter.hasNext()) { + ++totalLoaded; + row = iter.next(); + UserRole ur = creator.create(row); + visit.visit(ur); + } + } + + public static class DataLoadVisitor implements Visitor { + @Override + public void visit(UserRole ur) { + data.add(ur); + + List lur = byUser.get(ur.urdd.user); + if (lur==null) { + lur = new ArrayList<>(); + byUser.put(ur.urdd.user, lur); + } + lur.add(ur); + + lur = byRole.get(ur.urdd.role); + if (lur==null) { + lur = new ArrayList<>(); + byRole.put(ur.urdd.role, lur); + } + lur.add(ur); + } + } + + public int totalLoaded() { + return totalLoaded; + } + + public int deleted() { + return deleted; + } + + @Override + public void expunge() { + data.remove(this); + + List lur = byUser.get(urdd.user); + if (lur!=null) { + lur.remove(this); + } + + lur = byRole.get(urdd.role); + if (lur!=null) { + lur.remove(this); + } + } + + public static void setDeleteStream(PrintStream ds) { + urDelete = ds; + } + + public static void setRecoverStream(PrintStream ds) { + urRecover = ds; + } + + public static long count(Trans trans, Session session) { + String query = "select count(*) from authz.user_role LIMIT 1000000;"; + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); + } finally { + tt.done(); + } + } + + public UserRoleDAO.Data urdd() { + return urdd; + } + + public String user() { + return urdd.user; + } + + public String role() { + return urdd.role; + } + + public String ns() { + return urdd.ns; + } + + public String rname() { + return urdd.rname; + } + + public Date expires() { + return urdd.expires; + } + + public void expires(Date time) { + urdd.expires = time; + } + + public String toString() { + return "\"" + urdd.user + SEPARATOR + urdd.role + SEPARATOR + urdd.ns + SEPARATOR + urdd.rname + SEPARATOR + + Chrono.dateOnlyStamp(urdd.expires); + } + + public static UserRole get(String u, String r) { + List lur = byUser.get(u); + if (lur!=null) { + for (UserRole ur : lur) { + + if (ur.urdd.role.equals(r)) { + return ur; + } + } + } + return null; + } + + // SAFETY - DO NOT DELETE USER ROLES DIRECTLY FROM BATCH FILES!!! + // We write to a file, and validate. If the size is iffy, we email Support + public void delayDelete(AuthzTrans trans, String text, boolean dryRun) { + String dt = Chrono.dateTime(urdd.expires); + if (dryRun) { + trans.info().printf(LOG_FMT,text,"Would Delete",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); + } else { + trans.info().printf(LOG_FMT,text,"Staged Deletion",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); + } + urDelete.printf(DELETE_FMT,text,urdd.user,urdd.role,dt,urdd.ns,urdd.rname); + urRecover.printf(REPLAY_FMT,urdd.user,urdd.role,dt,urdd.ns,urdd.rname); + + cache.delayedDelete(this); + ++deleted; + } + + + /** + * Calls expunge() for all deleteCached entries + */ + public static void resetLocalData() { + cache.resetLocalData(); + } + + public static int sizeForDeletion() { + return cache.cacheSize(); + } + + public static boolean pendingDelete(UserRole ur) { + return cache.contains(ur); + } + + public static void actuateDeletionNow(AuthzTrans trans, URDelete directDel) { + for (UserRole ur : cache.getRemoved()) { + directDel.exec(trans, ur, "Actuating UserRole Deletion"); + } + cache.getRemoved().clear(); + cache.resetLocalData(); + } + + public void row(final CSV.Writer csvw) { + csvw.row("ur",user(),ns(),rname(),Chrono.dateOnlyStamp(expires())); + } + + public static void row(StringBuilder sb, List row) { + sb.append("DELETE from authz.user_role WHERE user='"); + sb.append(row.get(1)); + sb.append("' AND role='"); + sb.append(row.get(2)); + sb.append('.'); + sb.append(row.get(3)); + sb.append("';\n"); + } + + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java new file mode 100644 index 00000000..a59064ee --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java @@ -0,0 +1,25 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.aaf.auth.batch.helpers; + +public interface Visitor { + void visit(T t); +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java new file mode 100644 index 00000000..8bdcd100 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java @@ -0,0 +1,119 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.cert.X509Certificate; +import java.util.Iterator; +import java.util.List; + +import org.onap.aaf.cadi.Hash; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; +import org.onap.aaf.misc.env.util.Chrono; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; + +public class X509 { + public final String ca,id,x500,x509; + public ByteBuffer serial; + + public X509(String ca, String id, String x500, String x509, ByteBuffer serial) { + this.ca = ca; + this.id = id; + this.x500 = x500; + this.x509 = x509; + this.serial = serial; + } + + + public static void load(Trans trans, Session session, Visitor visitor) { + load(trans,session,"select ca, id, x500, x509, serial from authz.x509;", visitor); + } + + private static void load(Trans trans, Session session, String query, Visitor visitor) { + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Read Roles", Env.REMOTE); + + ResultSet results; + try { + Statement stmt = new SimpleStatement( query ); + results = session.execute(stmt); + } finally { + tt.done(); + } + + int count = 0; + try { + Iterator iter = results.iterator(); + Row row; + tt = trans.start("Load X509s", Env.SUB); + try { + while (iter.hasNext()) { + ++count; + row = iter.next(); + visitor.visit(new X509(row.getString(0),row.getString(1), row.getString(2),row.getString(3),row.getBytes(4))); + } + } finally { + tt.done(); + } + } finally { + trans.info().log("Found",count,"X509 Certificates"); + } + } + + public static long count(Trans trans, Session session) { + String query = "select count(*) from authz.x509 LIMIT 1000000;"; + trans.info().log( "query: " + query ); + TimeTaken tt = trans.start("Count x509s", Env.REMOTE); + ResultSet results; + try { + Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); + results = session.execute(stmt); + return results.one().getLong(0); + } finally { + tt.done(); + } + } + + + public void row(CSV.Writer cw, X509Certificate x509Cert) throws IOException { + cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500); + } + + + public static void row(StringBuilder sb, List row) throws IOException { + sb.append("DELETE from authz.x509 WHERE ca='"); + sb.append(row.get(1)); + sb.append("' AND serial="); + sb.append(row.get(2)); + sb.append(";\n"); + } + +} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Expiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Expiring.java new file mode 100644 index 00000000..1a7db055 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Expiring.java @@ -0,0 +1,301 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.reports; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.batch.helpers.Cred; +import org.onap.aaf.auth.batch.helpers.ExpireRange; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.batch.helpers.Visitor; +import org.onap.aaf.auth.batch.helpers.X509; +import org.onap.aaf.auth.batch.helpers.Cred.Instance; +import org.onap.aaf.auth.batch.helpers.ExpireRange.Range; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.cadi.configure.Factory; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; + + +public class Expiring extends Batch { + + private static final String CSV = ".csv"; + private static final String INFO = "info"; + private static final String EXPIRED_OWNERS = "ExpiredOwners"; + private int minOwners; + private Map writerList; + private File logDir; + private ExpireRange expireRange; + private Date deleteDate; + + public Expiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + + // Load Cred. We don't follow Visitor, because we have to gather up everything into Identity Anyway + Cred.load(trans, session); + UserRole.load(trans, session, UserRole.v2_0_11, new UserRole.DataLoadVisitor()); + + minOwners=1; + + // Create Intermediate Output + writerList = new HashMap<>(); + logDir = new File(logDir()); + logDir.mkdirs(); + + expireRange = new ExpireRange(trans.env().access()); + String sdate = Chrono.dateOnlyStamp(expireRange.now); + for( List lr : expireRange.ranges.values()) { + for(Range r : lr ) { + if(writerList.get(r.name())==null) { + File file = new File(logDir,r.name() + sdate +CSV); + CSV csv = new CSV(file); + CSV.Writer cw = csv.writer(false); + cw.row(INFO,r.name(),Chrono.dateOnlyStamp(expireRange.now),r.reportingLevel()); + writerList.put(r.name(),cw); + if("Delete".equals(r.name())) { + deleteDate = r.getStart(); + } + } + } + } + + } finally { + tt0.done(); + } + } + + @Override + protected void run(AuthzTrans trans) { + try { + File file = new File(logDir, EXPIRED_OWNERS + Chrono.dateOnlyStamp(expireRange.now) + CSV); + final CSV ownerCSV = new CSV(file); + + Map> owners = new TreeMap>(); + trans.info().log("Process UserRoles"); + UserRole.load(trans, session, UserRole.v2_0_11, new Visitor() { + @Override + public void visit(UserRole ur) { + // Cannot just delete owners, unless there is at least one left. Process later + if ("owner".equals(ur.rname())) { + Set urs = owners.get(ur.role()); + if (urs == null) { + urs = new HashSet(); + owners.put(ur.role(), urs); + } + urs.add(ur); + } else { + writeAnalysis(trans,ur); + } + } + }); + + // Now Process Owners, one owner Role at a time, ensuring one is left, + // preferably + // a good one. If so, process the others as normal. Otherwise, write + // ExpiredOwners + // report + if (!owners.values().isEmpty()) { + // Lazy Create file + CSV.Writer expOwner = null; + try { + for (Set sur : owners.values()) { + int goodOwners = 0; + for (UserRole ur : sur) { + if (ur.expires().after(expireRange.now)) { + ++goodOwners; + } + } + + for (UserRole ur : sur) { + if (goodOwners >= minOwners) { + writeAnalysis(trans, ur); + } else { + if (expOwner == null) { + expOwner = ownerCSV.writer(); + expOwner.row(INFO,EXPIRED_OWNERS,Chrono.dateOnlyStamp(expireRange.now),2); + } + expOwner.row("owner",ur.role(), ur.user(), Chrono.dateOnlyStamp(ur.expires())); + } + } + } + } finally { + if(expOwner!=null) { + expOwner.close(); + } + } + } + + trans.info().log("Checking for Expired Credentials"); + + for (Cred cred : Cred.data.values()) { + List linst = cred.instances; + if(linst!=null) { + Instance lastBath = null; + for(Instance inst : linst) { + // Special Behavior: only eval the LAST Instance + if (inst.type == CredDAO.BASIC_AUTH || inst.type == CredDAO.BASIC_AUTH_SHA256) { + if(deleteDate!=null && inst.expires.before(deleteDate)) { + writeAnalysis(trans, cred, inst); // will go to Delete + } else if(lastBath==null || lastBath.expires.before(inst.expires)) { + lastBath = inst; + } + } else { + writeAnalysis(trans, cred, inst); + } + } + if(lastBath!=null) { + writeAnalysis(trans, cred, lastBath); + } + } + } + + trans.info().log("Checking for Expired X509s"); + X509.load(trans, session, new Visitor() { + @Override + public void visit(X509 x509) { + try { + for(Certificate cert : Factory.toX509Certificate(x509.x509)) { + writeAnalysis(trans, x509, (X509Certificate)cert); + } + } catch (CertificateException | IOException e) { + trans.error().log(e, "Error Decrypting X509"); + } + + } + }); + } catch (FileNotFoundException e) { + trans.info().log(e); + } + } + + + private void writeAnalysis(AuthzTrans trans, UserRole ur) { + Range r = expireRange.getRange("ur", ur.expires()); + if(r!=null) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + ur.row(cw); + } + } + } + + private void writeAnalysis(AuthzTrans trans, Cred cred, Instance inst) { + if(cred!=null && inst!=null) { + Range r = expireRange.getRange("cred", inst.expires); + if(r!=null) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + cred.row(cw,inst); + } + } + } + } + + private void writeAnalysis(AuthzTrans trans, X509 x509, X509Certificate x509Cert) throws IOException { + Range r = expireRange.getRange("x509", x509Cert.getNotAfter()); + if(r!=null) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + x509.row(cw,x509Cert); + } + } + } + + /* + private String[] contacts(final AuthzTrans trans, final String ns, final int levels) { + List owners = UserRole.getByRole().get(ns+".owner"); + List current = new ArrayList<>(); + for(UserRole ur : owners) { + if(expireRange.now.before(ur.expires())) { + current.add(ur); + } + } + if(current.isEmpty()) { + trans.warn().log(ns,"has no current owners"); + current = owners; + } + + List email = new ArrayList<>(); + for(UserRole ur : current) { + Identity id; + int i=0; + boolean go = true; + try { + id = org.getIdentity(trans, ur.user()); + do { + if(id!=null) { + email.add(id.email()); + if(i la : Approval.byUser.values()) { + for (Approval a : la ) { + memo = a.getMemo(); + if (memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { + String role = a.getRole(); + if (role!=null) { + UserRole ur = UserRole.get(a.getUser(), a.getRole()); + Future f=null; + if (ur!=null) { + if (ur.expires().after(future)) { // no need for Approval anymore + a.delayDelete(noAvg, apprDAO, dryRun, "User Role already Extended"); + UUID tkt = a.getTicket(); + if (tkt!=null && Future.data.containsKey(tkt)) { + f = Future.data.get(a.getTicket()); + } + } + } else { + a.delayDelete(noAvg, apprDAO, dryRun, "User Role does not exist"); + UUID tkt = a.getTicket(); + if (tkt !=null && Future.data.containsKey(tkt)) { + f = Future.data.get(a.getTicket()); + } + } + if (f!=null) { + f.delayedDelete(noAvg, futureDAO, dryRun, "Approvals removed"); + } + } + } + } + } + try { + trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); + Future.resetLocalData(); + Approval.resetLocalData(); + } catch (Exception t) { + t.printStackTrace(); + } + + // Run for Expired Futures + trans.info().log("Checking for Expired Approval/Futures"); + tt = trans.start("Delete old Futures", Env.REMOTE); + trans.info().log("### Running Future Execution on ",Future.data.size(), "Items"); + // Execute any Futures waiting + for (Future f : Future.data.values()) { + if (f.memo().contains("Re-Approval") || f.memo().contains("Re-Validate")) { + List la = Approval.byTicket.get(f.id()); + if (la!=null) { + Result ruf = urFutureApproveExec.exec(noAvg,la,f); + if (ruf.isOK()) { + switch(ruf.value) { + case P: + break; + case E: + case D: + case L: + f.delayedDelete(noAvg, futureDAO, dryRun,OP_STATUS.L.desc()); + Approval.delayDelete(noAvg, apprDAO, dryRun, la,OP_STATUS.L.desc()); + break; + } + } + } + } + } + try { + trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); + Future.resetLocalData(); + Approval.resetLocalData(); + } catch (Exception t) { + t.printStackTrace(); + } + + + trans.info().log("### Remove Expired on ",Future.data.size(), "Items, or premature ones"); + // Remove Expired + String expiredBeforeNow = "Expired before " + tooLate; + String expiredAfterFuture = "Expired after " + future; + try { + for (Future f : Future.data.values()) { + if (f.expires().before(tooLate)) { + f.delayedDelete(noAvg,futureDAO,dryRun, expiredBeforeNow); + Approval.delayDelete(noAvg, apprDAO, dryRun, Approval.byTicket.get(f.id()), expiredBeforeNow); + } else if (f.expires().after(future)) { + f.delayedDelete(noAvg,futureDAO,dryRun, expiredAfterFuture); + Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), expiredAfterFuture); + } + } + try { + trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); + Future.resetLocalData(); + Approval.resetLocalData(); + } catch (Exception t) { + t.printStackTrace(); + } + } finally { + tt.done(); + } + + trans.info().log("### Checking Approvals valid (",Approval.byApprover.size(),"Items)"); + // Make sure users of Approvals are still valid + for (List lapp : Approval.byTicket.values()) { + for (Approval app : lapp) { + Future f; + if (app.getTicket()==null) { + f = null; + } else { + f = Future.data.get(app.getTicket()); + if (Future.pendingDelete(f)) { + f=null; + } + } + String msg; + if (f!=null && app.getRole()!=null && Role.byName.get(app.getRole())==null) { + f.delayedDelete(noAvg,futureDAO,dryRun,msg="Role '" + app.getRole() + "' no longer exists"); + Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); + continue; + } + + switch(app.getStatus()) { + case "pending": + if (f==null) { + app.delayDelete(noAvg,apprDAO, isDryRun(), "ticketDeleted"); + continue; + } + switch(app.getType()) { + case "owner": + boolean anOwner=false; + String approle = app.getRole(); + if (approle!=null) { + Role role = Role.byName.get(approle); + if (role==null) { + app.delayDelete(noAvg, apprDAO, dryRun, "Role No Longer Exists"); + continue; + } else { + // Make sure Owner Role exists + String owner = role.ns + ".owner"; + if (Role.byName.containsKey(owner)) { + List lur = UserRole.getByRole().get(owner); + if (lur != null) { + for (UserRole ur : lur) { + if (ur.user().equals(app.getApprover())) { + anOwner = true; + break; + } + } + } + } + } + if (!anOwner) { + app.delayDelete(noAvg, apprDAO, dryRun, "No longer Owner"); + } + + } + break; + case "supervisor": + try { + Identity identity = org.getIdentity(noAvg, app.getUser()); + if (identity==null) { + if (f!=null) { + f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getUser() + " is no longer associated with " + org.getName()); + Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); + } + } else { + if (!app.getApprover().equals(identity.responsibleTo().fullID())) { + if (f!=null) { + f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getApprover() + " is no longer a Supervisor of " + app.getUser()); + Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); + } + } + } + } catch (OrganizationException e) { + e.printStackTrace(); + } + break; + } + break; + } + } + } + try { + trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); + Future.resetLocalData(); + Approval.resetLocalData(); + } catch (Exception t) { + t.printStackTrace(); + } + + int count = 0, deleted=0, delayedURDeletes = 0; + + // Run for User Roles + trans.info().log("Checking for Expired User Roles"); + try { + for (UserRole ur : UserRole.getData()) { + if (org.getIdentity(noAvg, ur.user())==null) { // if not part of Organization; + if (isSpecial(ur.user())) { + trans.info().log(ur.user(),"is not part of organization, but may not be deleted"); + } else { + ur.delayDelete(noAvg, "Not Part of Organization", dryRun); + ++deleted; + ++delayedURDeletes; + } + } else { + if (NS.data.get(ur.ns())==null) { + ur.delayDelete(noAvg,"Namespace " + ur.ns() + " does not exist.",dryRun); + ++delayedURDeletes; + ++deleted; + } else if (!Role.byName.containsKey(ur.role())) { + ur.delayDelete(noAvg,"Role " + ur.role() + " does not exist.",dryRun); + ++deleted; + ++delayedURDeletes; + } else if (ur.expires().before(tooLate)) { + if ("owner".equals(ur.rname())) { // don't delete Owners, even if Expired + urPrint.exec(noAvg,ur,"Owner Expired (but not deleted)"); + } else { + // In this case, when UR is expired, not dependent on other lookups, we delete straight out. + urDelete.exec(noAvg, ur,"Expired before " + tooLate); + ++deleted; + } + //trans.logAuditTrail(trans.info()); + } else if (ur.expires().before(future) && ur.expires().after(now)) { + ++count; + // Is there an Approval set already + boolean needNew = true; + if (ur.role()!=null && ur.user()!=null) { + List abm = Approval.byUser.get(ur.user()); + if (abm!=null) { + for (Approval a : abm) { + if (a.getOperation().equals(FUTURE_OP.A.name()) && ur.role().equals(a.getRole())) { + if (Future.data.get(a.getTicket())!=null) { + needNew = false; + break; + } + } + } + } + } + if (needNew) { + urFutureApprove.exec(noAvg, ur,""); + } + } + } + } + } catch (OrganizationException e) { + env.info().log(e,"Exiting ..."); + } finally { + env.info().log("Found",count,"user roles expiring before",future); + env.info().log("deleting",deleted,"user roles expiring before",tooLate); + } + + // Actualize UR Deletes, or send Email + if (UserRole.sizeForDeletion()>0) { + count+=UserRole.sizeForDeletion(); + double onePercent = 0.01; + if (((double)UserRole.sizeForDeletion())/UserRole.getData().size() > onePercent) { + Message msg = new Message(); + try { + msg.line("Found %d of %d UserRoles marked for Deletion in file %s", + delayedURDeletes,UserRole.getData().size(),deletesFile.getCanonicalPath()); + } catch (IOException e) { + msg.line("Found %d of %d UserRoles marked for Deletion.\n", + delayedURDeletes); + } + msg.line("Review the File. If data is ok, Use ExpiringP2 BatchProcess to complete the deletions"); + + email.msg(msg); + email.exec(trans, org, "Email Support"); + } else { + urDeleteF.flush(); + try { + BufferedReader br = new BufferedReader(new FileReader(deletesFile)); + try { + ExpiringP2.deleteURs(noAvg, br, urDelete, null /* don't touch Cache here*/); + } finally { + br.close(); + } + } catch (IOException io) { + noAvg.error().log(io); + } + } + } + if (count>0) { + String str = String.format("%d UserRoles modified or deleted", count); + cacheTouch.exec(trans, "user_role", str); + } + + // Run for Creds + trans.info().log("Checking for Expired Credentials"); + System.out.flush(); + count = 0; + try { + CredDAO.Data crd = new CredDAO.Data(); + Date last = null; + for ( Cred creds : Cred.data.values()) { + crd.id = creds.id; + for (int type : creds.types()) { + crd.type = type; + for ( Instance inst : creds.instances) { + if (inst.expires.before(tooLate)) { + crd.expires = inst.expires; + crDelete.exec(noAvg, crd,"Expired before " + tooLate); + } else if (last==null || inst.expires.after(last)) { + last = inst.expires; + } + } + if (last!=null) { + if (last.before(future)) { + crd.expires = last; + crPrint.exec(noAvg, crd,""); + ++count; + } + } + } + } + } finally { + String str = String.format("Found %d current creds expiring before %s", count, Chrono.dateOnlyStamp(future)); + if (count>0) { + cacheTouch.exec(trans, "cred", str); + } + } + + } + + @Override + protected void _close(AuthzTrans trans) { + trans.info().log("End",this.getClass().getSimpleName(),"processing" ); + for (Action action : new Action[] {crDelete}) { + if (action instanceof ActionDAO) { + ((ActionDAO)action).close(trans); + } + } + session.close(); + urDeleteF.close(); + urRecoverF.close(); + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/ExpiringP2.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/ExpiringP2.java new file mode 100644 index 00000000..a75f0a1c --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/ExpiringP2.java @@ -0,0 +1,158 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.update; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.batch.BatchPrincipal; +import org.onap.aaf.auth.batch.actions.Action; +import org.onap.aaf.auth.batch.actions.ActionDAO; +import org.onap.aaf.auth.batch.actions.CacheTouch; +import org.onap.aaf.auth.batch.actions.URDelete; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.cadi.util.Split; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; + +public class ExpiringP2 extends Batch { + private final URDelete urDelete; + private final CacheTouch cacheTouch; + private final AuthzTrans noAvg; + private final BufferedReader urDeleteF; + + public ExpiringP2(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("batch:ExpiringP2")); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + urDelete = new URDelete(trans, cluster,isDryRun()); + TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = urDelete.getSession(trans); + } finally { + tt2.done(); + } + cacheTouch = new CacheTouch(trans,urDelete); + + File data_dir = new File(env.getProperty("aaf_data_dir")); + if (!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { + throw new IOException("Cannot read/write to Data Directory "+ data_dir.getCanonicalPath() + ": EXITING!!!"); + } + urDeleteF = new BufferedReader(new FileReader(new File(data_dir,"UserRoleDeletes.dat"))); + + } finally { + tt0.done(); + } + } + + @Override + protected void run(AuthzTrans trans) { + deleteURs(noAvg, urDeleteF, urDelete, cacheTouch); + } + + public static void deleteURs(AuthzTrans trans, BufferedReader urDeleteF, URDelete urDelete, CacheTouch cacheTouch) { + String line,prev=""; + try { + UserRole ur; + Map tally = new HashMap<>(); + int count=0; + try { + while ((line=urDeleteF.readLine())!=null) { + if (line.startsWith("#")) { + Count cnt = tally.get(line); + if (cnt==null) { + tally.put(line, cnt=new Count()); + } + cnt.inc(); + prev = line; + } else { + String[] l = Split.splitTrim('|', line); + try { + // Note: following default order from "COPY TO" + ur = new UserRole(l[0],l[1],l[3],l[4],Chrono.iso8601Fmt.parse(l[2])); + urDelete.exec(trans, ur, prev); + ++count; + } catch (ParseException e) { + trans.error().log(e); + } + } + } + + System.out.println("Tallies of UserRole Deletions"); + for (Entry es : tally.entrySet()) { + System.out.printf(" %6d\t%20s\n", es.getValue().cnt,es.getKey()); + } + } finally { + if (cacheTouch!=null && count>0) { + cacheTouch.exec(trans, "user_roles", "Removing UserRoles"); + } + } + } catch (IOException e) { + trans.error().log(e); + } + + } + private static class Count { + private int cnt=0; + + public /*synchonized*/ void inc() { + ++cnt; + } + + public String toString() { + return Integer.toString(cnt); + } + } + + @Override + protected void _close(AuthzTrans trans) { + trans.info().log("End",this.getClass().getSimpleName(),"processing" ); + for (Action action : new Action[] {urDelete,cacheTouch}) { + if (action instanceof ActionDAO) { + ((ActionDAO)action).close(trans); + } + } + session.close(); + try { + urDeleteF.close(); + } catch (IOException e) { + trans.error().log(e); + } + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyApprovals.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyApprovals.java new file mode 100644 index 00000000..c88eecde --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyApprovals.java @@ -0,0 +1,236 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.update; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Map.Entry; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.batch.BatchPrincipal; +import org.onap.aaf.auth.batch.actions.Email; +import org.onap.aaf.auth.batch.actions.EmailPrint; +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.batch.helpers.Approval; +import org.onap.aaf.auth.batch.helpers.Future; +import org.onap.aaf.auth.dao.CassAccess; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.dao.cass.HistoryDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.org.OrganizationFactory; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.util.Chrono; + +public class NotifyApprovals extends Batch { + private static final String LINE = "----------------------------------------------------------------"; + private final HistoryDAO historyDAO; + private final ApprovalDAO apprDAO; + private final FutureDAO futureDAO; + private Email email; + private int maxEmails; + private final PrintStream ps; + private final AuthzTrans noAvg; + + public NotifyApprovals(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("batch:NotifyApprovals")); + + historyDAO = new HistoryDAO(trans, cluster, CassAccess.KEYSPACE); + session = historyDAO.getSession(trans); + apprDAO = new ApprovalDAO(trans, historyDAO); + futureDAO = new FutureDAO(trans, historyDAO); + if (isDryRun()) { + email = new EmailPrint(); + maxEmails=3; + } else { + email = new Email(); + maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); + } + email.subject("AAF Approval Notification (ENV: %s)",batchEnv); + email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications." + + "\n Your approval is required, which you may enter on the following page:" + + "\n\n\t%s/approve\n\n" + ,env.getProperty(GUI_URL)); + email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n" + + "https://wiki.web.att.com/display/aaf/Contact+Us\n" + + "(Use 'Other Misc Requests (TOPS)')"); + + Approval.load(trans, session, Approval.v2_0_17); + Future.load(trans, session, Future.v2_0_17); // Skip the Construct Data + + ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true)); + ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":""); + } + + @Override + protected void run(AuthzTrans trans) { + GregorianCalendar gc = new GregorianCalendar(); + Date now = gc.getTime(); + String today = Chrono.dateOnlyStamp(now); + gc.add(GregorianCalendar.MONTH, -1); + gc=null; + + + Message msg = new Message(); + int emailCount = 0; + List pending = new ArrayList<>(); + boolean isOwner,isSupervisor; + for (Entry> es : Approval.byApprover.entrySet()) { + isOwner = isSupervisor = false; + String approver = es.getKey(); + if (approver.indexOf('@')<0) { + approver += org.getRealm(); + } + Date latestNotify=null, soonestExpire=null; + GregorianCalendar latest=new GregorianCalendar(); + GregorianCalendar soonest=new GregorianCalendar(); + pending.clear(); + + for (Approval app : es.getValue()) { + Future f = app.getTicket()==null?null:Future.data.get(app.getTicket()); + if (f==null) { // only Ticketed Approvals are valid.. the others are records. + // Approvals without Tickets are no longer valid. + if ("pending".equals(app.getStatus())) { + app.setStatus("lapsed"); + app.update(noAvg,apprDAO,dryRun); // obeys dryRun + } + } else { + if ((soonestExpire==null && f.expires()!=null) || (soonestExpire!=null && f.expires()!=null && soonestExpire.before(f.expires()))) { + soonestExpire=f.expires(); + } + + if ("pending".equals(app.getStatus())) { + if (!isOwner) { + isOwner = "owner".equals(app.getType()); + } + if (!isSupervisor) { + isSupervisor = "supervisor".equals(app.getType()); + } + + if ((latestNotify==null && app.getLast_notified()!=null) ||(latestNotify!=null && app.getLast_notified()!=null && latestNotify.before(app.getLast_notified()))) { + latestNotify=app.getLast_notified(); + } + pending.add(app); + } + } + } + + if (!pending.isEmpty()) { + boolean go = false; + if (latestNotify==null) { // never notified... make it so + go=true; + } else { + if (!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today + latest.setTime(latestNotify); + soonest.setTime(soonestExpire); + int year; + int days = soonest.get(GregorianCalendar.DAY_OF_YEAR)-latest.get(GregorianCalendar.DAY_OF_YEAR); + days+=((year=soonest.get(GregorianCalendar.YEAR))-latest.get(GregorianCalendar.YEAR))*365 + + (soonest.isLeapYear(year)?1:0); + if (days<7) { // If Expirations get within a Week (or expired), notify everytime. + go = true; + } + } + } + if (go) { + if (maxEmails>emailCount++) { + try { + Organization org = OrganizationFactory.obtain(env, approver); + Identity user = org.getIdentity(noAvg, approver); + if (user==null) { + ps.printf("Invalid Identity: %s\n", approver); + } else { + email.clear(); + msg.clear(); + email.addTo(user.email()); + msg.line(LINE); + msg.line("Why are you receiving this Notification?\n"); + if (isSupervisor) { + msg.line("%sYou are the supervisor of one or more employees who need access to tools which are protected by AAF. " + + "Your employees may ask for access to various tools and applications to do their jobs. ASPR requires " + + "that you are notified and approve their requests. The details of each need is provided when you click " + + "on webpage above.\n",isOwner?"1) ":""); + msg.line("Your participation in this process fulfills the ASPR requirement to re-authorize users in roles on a regular basis.\n\n"); + } + + if (isOwner) { + msg.line("%sYou are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " + + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. " + + "More info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n",isSupervisor?"2) ":""); + msg.line("Additionally, Credentials attached to the Namespace must be renewed regularly. While you may delegate certain functions to " + + "Administrators within your Namespace, you are ultimately responsible to make sure credentials do not expire.\n"); + msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n"); + msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); + + } + msg.line(" If you are unfamiliar with AAF, you might like to peruse the following links:" + + "\n\thttps://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell" + + "\n\thttps://wiki.web.att.com/display/aaf/The+New+Person%%27s+Guide+to+AAF"); + msg.line("\n SPECIAL NOTE about SWM Management Groups: Understand that SWM management Groups correlate one-to-one to AAF Namespaces. " + + "(SWM uses AAF for the Authorization piece of Management Groups). You may be assigned the SWM Management Group by asking " + + "directly, or through any of the above stated automated processes. Auto-generated Namespaces typically look like 'com.att.44444.PROD' " + + "where '44444' is a MOTS ID, and 'PROD' is PROD|DEV|TEST, etc. For your convenience, the MOTS link is http://ebiz.sbc.com/mots.\n"); + msg.line(" Finally, realize that there are automated processes which create Machines and Resources via SWM, Kubernetes or other " + + "such tooling. If you or your predecessor requested them, you were set as the owner of the AAF Namespace created during " + + "that process.\n"); + msg.line(" For ALL QUESTIONS of why and how of SWM, and whether you or your reports can be removed, please contact SWM at " + + "https://wiki.web.att.com/display/swm/Support\n"); + + email.msg(msg); + email.exec(noAvg, org,""); + if (!isDryRun()) { + email.log(ps,"NotifyApprovals"); + for (Approval app : pending) { + app.setLastNotified(now); + app.update(noAvg, apprDAO, dryRun); + } + } + } + } catch (OrganizationException e) { + trans.info().log(e); + } + } + } + } + } + trans.info().printf("%d emails sent for %s", emailCount,batchEnv); + } + + @Override + protected void _close(AuthzTrans trans) { + futureDAO.close(trans); + apprDAO.close(trans); + historyDAO.close(trans); + ps.close(); + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyCredExpiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyCredExpiring.java new file mode 100644 index 00000000..ab7525b6 --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/NotifyCredExpiring.java @@ -0,0 +1,394 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.update; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.batch.BatchPrincipal; +import org.onap.aaf.auth.batch.actions.Email; +import org.onap.aaf.auth.batch.actions.EmailPrint; +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.batch.helpers.Cred; +import org.onap.aaf.auth.batch.helpers.NS; +import org.onap.aaf.auth.batch.helpers.Notification; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.batch.helpers.Notification.TYPE; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.hl.Question; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.auth.org.EmailWarnings; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.org.OrganizationFactory; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; + + +public class NotifyCredExpiring extends Batch { + + private static final String UNKNOWN_ID = "unknown@deprecated.id"; + private static final String AAF_INSTANTIATED_MECHID = "AAF INSTANTIATED MECHID"; + private static final String EXPIRATION_DATE = "EXPIRATION DATE"; + private static final String QUICK_LINK = "QUICK LINK TO UPDATE PAGE"; + private static final String DASH_1 = "-----------------------"; + private static final String DASH_2 = "---------------"; + private static final String DASH_3 = "----------------------------------------------------"; + private static final String LINE = "\n----------------------------------------------------------------"; + private Email email; + private int maxEmails; + private final PrintStream ps; + private final AuthzTrans noAvg; + private String supportEmailAddr; + private CSV csv; + private CSVInfo csvInfo; + + public NotifyCredExpiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring")); + + if (isDryRun()) { + email = new EmailPrint(); + maxEmails=3; + maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); + } else { + email = new Email(); + maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); + } + + email.subject("AAF Password Expiration Notification (ENV: %s)",batchEnv); + email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications.\n\n" + + " The following Credentials are expiring on the dates shown. Failure to act before the expiration date " + + "will cause your App's Authentications to fail.\n"); + email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n" + + "https://wiki.web.att.com/display/aaf/Contact+Us\n" + + "(Use 'Other Misc Requests (TOPS)')"); + + boolean quit = false; + if(args().length<1) { + System.err.println("Need CSV formatted Expiring Report"); + quit = true; + } else { + File f = new File(logDir(),args()[0]); + System.out.println("Reading " + f.getCanonicalPath()); + csv = new CSV(f); + } + + if(args().length<2) { + System.err.println("Need Email Template"); + //quit = true; + } + if(quit) { + System.exit(2); + } + + csvInfo = new CSVInfo(System.err); + try { + csv.visit(csvInfo); + } catch (CadiException e) { + throw new APIException(e); + } + + Notification.load(trans, session, Notification.v2_0_18); + + ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true)); + ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":""); + } + + @Override + protected void run(AuthzTrans trans) { + + // Temp structures + Map> ownerCreds = new TreeMap<>(); + + + List noOwner = new ArrayList<>(); + ownerCreds.put(UNKNOWN_ID,noOwner); + int emailCount=0; + +// // Get a list of ONLY the ones needing email by Owner +// for (Entry> es : Cred.byNS.entrySet()) { +// for (Cred c : es.getValue()) { +// List ownerURList = UserRole.getByRole().get(es.getKey()+".owner"); +// if (ownerURList!=null) { +// for (UserRole ur:ownerURList) { +// String owner = ur.user(); +// List llc = ownerCreds.get(owner); +// if (llc==null) { +// ownerCreds.put(owner, (llc=new ArrayList<>())); +// } +// llc.add(new LastCred(c,last)); +// } +// } else { +// noOwner.add(new LastCred(c,last)); +// } +// } +// } +// +// boolean bCritical,bNormal,bEarly; +// Message msg = new Message(); +// Notification ownNotf; +// StringBuilder logMessage = new StringBuilder(); +// for (Entry> es : ownerCreds.entrySet()) { +// String owner = es.getKey(); +// boolean header = true; +// try { +// Organization org = OrganizationFactory.obtain(env, owner); +// Identity user = org.getIdentity(noAvg, owner); +// if (!UNKNOWN_ID.equals(owner) && user==null) { +// ps.printf("Invalid Identity: %s\n", owner); +// } else { +// logMessage.setLength(0); +// if (maxEmails>emailCount) { +// bCritical=bNormal=bEarly = false; +// email.clear(); +// msg.clear(); +// email.addTo(user==null?supportEmailAddr:user.email()); +// +// ownNotf = Notification.get(es.getKey(),TYPE.CN); +// if (ownNotf==null) { +// ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN); +// } +// last = ownNotf.last; +// // Get Max ID size for formatting purposes +// int length = AAF_INSTANTIATED_MECHID.length(); +// for (LastCred lc : es.getValue()) { +// length = Math.max(length, lc.cred.id.length()); +// } +// String id_exp_fmt = "\t%-"+length+"s %15s %s"; +// +// Collections.sort(es.getValue(),LastCred.COMPARE); +// for (LastCred lc : es.getValue()) { +// if (lc.last.after(must) && lc.last.before(early) && +// (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { +// if (!bEarly && header) { +// msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early. " +// + "You will be reminded next month\n"); +// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); +// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); +// header = false; +// } +// bEarly = true; +// } else if (lc.last.after(critical) && lc.last.before(must) && +// (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { +// if (!bNormal) { +// boolean last2wks = lc.last.before(within2Weeks); +// if (last2wks) { +// try { +// Identity supvsr = user.responsibleTo(); +// email.addCC(supvsr.email()); +// } catch (OrganizationException e) { +// trans.error().log(e, "Supervisor cannot be looked up"); +// } +// } +// if (header) { +// msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" + +// (last2wks?"\tNote: Your Supervisor is CCd\n":"\tNote: Your Supervisor will be notified if this is not being done before the last 2 weeks\n")); +// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); +// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); +// } +// header = false; +// } +// bNormal=true; +// } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor +// if (!bCritical && header) { +// msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" + +// "\tYour supervisor is added to this Email\n"); +// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); +// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); +// header = false; +// } +// bCritical = true; +// try { +// if (user!=null) { +// Identity supvsr = user.responsibleTo(); +// if (supvsr!=null) { +// email.addCC(supvsr.email()); +// supvsr = supvsr.responsibleTo(); +// if (supvsr!=null) { +// email.addCC(supvsr.email()); +// } +// } +// } +// } catch (OrganizationException e) { +// trans.error().log(e, "Supervisor cannot be looked up"); +// } +// } +// if (bEarly || bNormal || bCritical) { +// if (logMessage.length()==0) { +// logMessage.append("NotifyCredExpiring"); +// } +// logMessage.append("\n\t"); +// logMessage.append(lc.cred.id); +// logMessage.append('\t'); +// logMessage.append(Chrono.dateOnlyStamp(lc.last)); +// msg.line(id_exp_fmt, lc.cred.id, Chrono.dateOnlyStamp(lc.last)+" ",env.getProperty(GUI_URL)+"/creddetail?ns="+Question.domain2ns(lc.cred.id)); +// } +// } +// +// if (bEarly || bNormal || bCritical) { +// msg.line(LINE); +// msg.line("Why are you receiving this Notification?\n"); +// msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " +// + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. " +// + "You might like https://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell. More detailed info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n"); +// msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n"); +// msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); +// email.msg(msg); +// Result rv = email.exec(trans, org,""); +// if (rv.isOK()) { +// ++emailCount; +// if (!isDryRun()) { +// ownNotf.update(noAvg, session, false); +// // SET LastNotification +// } +// email.log(ps,logMessage.toString()); +// } else { +// trans.error().log(rv.errorString()); +// } +// } +// } +// } +// } catch (OrganizationException e) { +// trans.info().log(e); +// } +// } + trans.info().printf("%d emails sent for %s", emailCount,batchEnv); + } + + + private static class CSVInfo implements CSV.Visitor { + private PrintStream out; + private Set unsupported; + private NotifyCredVisitor credv; + private List llc; + + public CSVInfo(PrintStream out) { + this.out = out; + credv = new NotifyCredVisitor(llc = new ArrayList<>()); + } + + @Override + public void visit(List row) throws IOException, CadiException { + + switch(row.get(0)) { + case NotifyCredVisitor.SUPPORTS: + credv.visit(row); + break; + default: + if(unsupported==null) { + unsupported = new HashSet(); + } + if(!unsupported.contains(row.get(0))) { + unsupported.add(row.get(0)); + out.println("Unsupported Type: " + row.get(0)); + } + } + } + } + + private static class Contact { + public List contacts; + private List owners; + + public Contact(final String ns) { + contacts = new ArrayList<>(); + loadFromNS(ns); + } + + public void loadFromNS(final String ns) { + owners = UserRole.getByRole().get(ns+".owner"); + } + } + + private static class LastCred extends Contact { + public final String id; + public final int type; + public final Date expires; + + public LastCred(final String id, final String ns, final int type, final Date expires) { + super(ns); + this.id = id; + this.type = type; + this.expires = expires; + } + } + + private static class NotifyCredVisitor implements CSV.Visitor { + public static final String SUPPORTS = "cred"; + private final List lastCred; + + public NotifyCredVisitor(final List lastCred) { + this.lastCred = lastCred; + } + + @Override + public void visit(List row) throws IOException, CadiException { + try { + lastCred.add(new LastCred( + row.get(1), + row.get(2), + Integer.parseInt(row.get(3)), + Chrono.dateOnlyFmt.parse(row.get(4)) + ) + ); + } catch (NumberFormatException | ParseException e) { + throw new CadiException(e); + } + } + } + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + ps.close(); + } +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java new file mode 100644 index 00000000..a884006c --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java @@ -0,0 +1,124 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.update; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.batch.BatchPrincipal; +import org.onap.aaf.auth.batch.actions.CacheTouch; +import org.onap.aaf.auth.batch.helpers.CQLBatch; +import org.onap.aaf.auth.batch.helpers.Cred; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.batch.helpers.X509; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.client.Holder; +import org.onap.aaf.cadi.util.CSV; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.util.Chrono; + +public class Remove extends Batch { + private final AuthzTrans noAvg; + private CacheTouch cacheTouch; + private CQLBatch cqlBatch; + + public Remove(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("batch:RemoveExpired")); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + cacheTouch = new CacheTouch(trans, cluster, dryRun); + TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cacheTouch.getSession(trans); + } finally { + tt2.done(); + } + cqlBatch = new CQLBatch(session); + + + } finally { + tt0.done(); + } + } + + @Override + protected void run(AuthzTrans trans) { + final int maxBatch = 50; + + // Create Intermediate Output + File logDir = new File(logDir()); + + File expired = new File(logDir,"Delete"+Chrono.dateOnlyStamp()+".csv"); + CSV expiredCSV = new CSV(expired); + try { + final StringBuilder sb = cqlBatch.begin(); + final Holder hi = new Holder(0); + expiredCSV.visit(new CSV.Visitor() { + @Override + public void visit(List row) throws IOException, CadiException { + int i = hi.get(); + if(i>=maxBatch) { + cqlBatch.execute(dryRun); + hi.set(0); + cqlBatch.begin(); + i=0; + } + switch(row.get(0)) { + case "ur": + hi.set(++i); + UserRole.row(sb,row); + break; + case "cred": + hi.set(++i); + Cred.row(sb,row); + break; + case "x509": + hi.set(++i); + X509.row(sb,row); + break; + } + } + }); + cqlBatch.execute(dryRun); + } catch (IOException | CadiException e) { + e.printStackTrace(); + } + } + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + cacheTouch.close(trans); + } + +} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java new file mode 100644 index 00000000..76472b5f --- /dev/null +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java @@ -0,0 +1,313 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.aaf.auth.batch.update; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.misc.env.APIException; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.TimeTaken; + +import com.datastax.driver.core.ResultSet; + +public class Upload extends Batch { + public Upload(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + + } finally { + tt0.done(); + } + } + + private static final int BATCH_LENGTH = 100; + + int count,batchCnt; + + @Override + protected void run(AuthzTrans trans) { + String line; + StringBuilder sb = new StringBuilder(); + StringBuilder query = new StringBuilder(); + List array = new ArrayList(); + for(String feed : args()) { + File file = new File(feed + ".dat"); + TimeTaken tt = trans.start(file.getAbsolutePath(), Env.SUB); + System.out.println("#### Running " + feed + ".dat Feed ####"); + try { + + if(file.exists()) { + count=batchCnt=0; + boolean justOne = false; + try { + BufferedReader br = new BufferedReader(new FileReader(file)); + try { + while((line=br.readLine())!=null) { + if(line.length()>5000) { + if(query.length()>0) { + applyBatch(query); + justOne=true; + } + } + if(query.length()==0) { + query.append("BEGIN BATCH\n"); + } + // Split into fields, first turning Escaped values into something we can convert back from + char c=0; + boolean inQuote = false; + int fldcnt = 0; + + for(int i=0;i0) { + applyBatch(query); + } + + } finally { + br.close(); + sb.setLength(0); + query.setLength(0); + } + + } catch (IOException e) { + trans.error().log(e); + e.printStackTrace(); + } + + } else { + trans.error().log("No file found: ", file.getAbsolutePath()); + } + } finally { + tt.done(); + System.err.flush(); + System.out.printf("\n%d applied in %d batches\n",count,batchCnt); + } + + } + + } + + // APPROVALS + private static final String APPR_INS_FMT=" INSERT INTO authz.approval " + + "(id,approver,last_notified,memo,operation,status,ticket,type,user) " + + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);\n"; + private static final Boolean[] APPR_QUOTES = new Boolean[]{false,true,true,true,true,true,false,true,true}; + + // ARTIFACTS + private static final String ARTI_INS_FMT=" INSERT INTO authz.artifact " + + "(mechid,machine,ca,dir,expires,notify,ns,os_user,renewdays,sans,sponsor,type) " + + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);\n"; + private static final Boolean[] ARTI_QUOTES = new Boolean[] + {true,true,true,true,true,true,true,true,false,false,true,false}; + + // CREDS + private static final String CRED_INS_FMT=" INSERT INTO authz.cred " + + "(id,type,expires,cred,notes,ns,other,prev) " + + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s);\n"; + private static final Boolean[] CRED_QUOTES = new Boolean[] + {true,false,true,false,true,true,false,false}; + + // NS + private static final String NS_INS_FMT=" INSERT INTO authz.ns " + + "(name,description,parent,scope,type) " + + "VALUES (%s,%s,%s,%s,%s);\n"; + private static final Boolean[] NS_QUOTES = new Boolean[] + {true,true,true,false,false}; + + // x509 + private static final String X509_INS_FMT=" INSERT INTO authz.x509 " + + "(ca,serial,id,x500,x509) " + + "VALUES (%s,%s,%s,%s,%s);\n"; + private static final Boolean[] X509_QUOTES = new Boolean[] + {true,false,true,true,true}; + + // ROLE + private static final String ROLE_INS_FMT=" INSERT INTO authz.role " + + "(ns,name,description,perms) " + + "VALUES (%s,%s,%s,%s);\n"; + private static final Boolean[] ROLE_QUOTES = new Boolean[] + {true,true,true,false}; + // ROLE + private static final String PERM_INS_FMT=" INSERT INTO authz.perm " + + "(ns,type,instance,action,description,roles) " + + "VALUES (%s,%s,%s,%s,%s,%s);\n"; + private static final Boolean[] PERM_QUOTES = new Boolean[] + {true,true,true,true,true,false}; + + + private String build(String feed, List array) { + String rv; + switch(feed) { + case "approval": + rv = String.format(APPR_INS_FMT,array.toArray()); + break; + case "artifact": + rv = String.format(ARTI_INS_FMT,array.toArray()); + break; + case "cred": + rv = String.format(CRED_INS_FMT,array.toArray()); + break; + case "ns": + rv = String.format(NS_INS_FMT,array.toArray()); + break; + case "role": + rv = String.format(ROLE_INS_FMT,array.toArray()); + break; + case "perm": + rv = String.format(PERM_INS_FMT,array.toArray()); + break; + case "x509": + rv = String.format(X509_INS_FMT,array.toArray()); + break; + default: + rv = ""; + } + array.clear(); + return rv; + } + + private void addField(String feed, int fldcnt, List array, StringBuilder sb) { + Boolean[] ba; + switch(feed) { + case "approval": + ba = APPR_QUOTES; + break; + case "artifact": + ba = ARTI_QUOTES; + break; + case "cred": + ba = CRED_QUOTES; + break; + case "ns": + ba = NS_QUOTES; + break; + case "role": + ba = ROLE_QUOTES; + break; + case "perm": + ba = PERM_QUOTES; + break; + case "x509": + ba = X509_QUOTES; + break; + default: + ba = null; + } + if(ba!=null) { + if(sb.toString().length()==0) { + array.add("null"); + } else { + if(ba[fldcnt]) { + String s = null; + if(sb.indexOf("'")>=0) { + s = sb.toString().replace("'","''"); + } + if(sb.indexOf("\\n")>=0) { + if(s==null) { + s = sb.toString().replace("\\n","\n"); + } else { + s = s.replace("\\n","\n"); + } + } + if(sb.indexOf("\\t")>=0) { + if(s==null) { + s = sb.toString().replace("\\t","\t"); + } else { + s = s.replace("\\t","\t"); + } + } + if(s==null) { + array.add("'" + sb + '\''); + } else { + array.add("'" + s + '\''); + } + } else { + array.add(sb.toString()); + } + } + sb.setLength(0); + } + } + + private void applyBatch(StringBuilder query) { + try { + query.append("APPLY BATCH;"); + ResultSet rv = session.execute(query.toString()); + if(rv.wasApplied()) { + System.out.print('.'); + if((++batchCnt % 60)==0) { + System.out.println(); + } + } else { + System.out.print("Data NOT APPLIED"); + } + } finally { + query.setLength(0); + } + } + + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + } + +} + diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java deleted file mode 100644 index a4c4efbc..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java +++ /dev/null @@ -1,309 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TreeMap; -import java.util.UUID; - -import org.onap.aaf.auth.dao.cass.ApprovalDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Approval implements CacheChange.Data { - public static final String RE_APPROVAL_IN_ROLE = "Re-Approval in Role '"; - public static final String RE_VALIDATE_ADMIN = "Re-Validate as Administrator for AAF Namespace '"; - public static final String RE_VALIDATE_OWNER = "Re-Validate Ownership for AAF Namespace '"; - - public static TreeMap> byApprover = new TreeMap<>(); - public static TreeMap> byUser = new TreeMap<>(); - public static TreeMap> byTicket = new TreeMap<>(); - private final static CacheChange cache = new CacheChange<>(); - - public final ApprovalDAO.Data add; - private String role; - - public Approval(UUID id, UUID ticket, String approver, Date last_notified, - String user, String memo, String operation, String status, String type, long updated) { - add = new ApprovalDAO.Data(); - add.id = id; - add.ticket = ticket; - add.approver = approver; - add.last_notified = last_notified; - add.user = user; - add.memo = memo; - add.operation = operation; - add.status = status; - add.type = type; - add.updated = new Date(updated); - role = roleFromMemo(memo); - } - - public static String roleFromMemo(String memo) { - if (memo==null) { - return null; - } - int first = memo.indexOf('\''); - if (first>=0) { - int second = memo.indexOf('\'', ++first); - if (second>=0) { - String role = memo.substring(first, second); - if (memo.startsWith(RE_VALIDATE_ADMIN)) { - return role + ".admin"; - } else if (memo.startsWith(RE_VALIDATE_OWNER)) { - return role + ".owner"; - } else if (memo.startsWith(RE_APPROVAL_IN_ROLE)) { - return role; - } - } - } - return null; - } - - public static void load(Trans trans, Session session, Creator creator ) { - trans.info().log( "query: " + creator.select() ); - TimeTaken tt = trans.start("Load Notify", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement(creator.select()); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - tt = trans.start("Process Notify", Env.SUB); - - try { - List ln; - for (Row row : results.all()) { - ++count; - try { - Approval app = creator.create(row); - String person = app.getApprover(); - if (person!=null) { - ln = byApprover.get(person); - if (ln==null) { - ln = new ArrayList<>(); - byApprover.put(app.getApprover(), ln); - } - ln.add(app); - } - - - person = app.getUser(); - if (person!=null) { - ln = byUser.get(person); - if (ln==null) { - ln = new ArrayList<>(); - byUser.put(app.getUser(), ln); - } - ln.add(app); - } - UUID ticket = app.getTicket(); - if (ticket!=null) { - ln = byTicket.get(ticket); - if (ln==null) { - ln = new ArrayList<>(); - byTicket.put(app.getTicket(), ln); - } - ln.add(app); - } - } finally { - tt.done(); - } - } - } finally { - tt.done(); - trans.info().log("Found",count,"Approval Records"); - } - } - - @Override - public void expunge() { - List la = byApprover.get(getApprover()); - if (la!=null) { - la.remove(this); - } - - la = byUser.get(getUser()); - if (la!=null) { - la.remove(this); - } - UUID ticket = this.add==null?null:this.add.ticket; - if (ticket!=null) { - la = byTicket.get(this.add.ticket); - if (la!=null) { - la.remove(this); - } - } - } - - public void update(AuthzTrans trans, ApprovalDAO apprDAO, boolean dryRun) { - if (dryRun) { - trans.info().printf("Would update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); - } else { - trans.info().printf("Update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); - apprDAO.update(trans, add); - } - } - - public static Creator v2_0_17 = new Creator() { - @Override - public Approval create(Row row) { - return new Approval(row.getUUID(0), row.getUUID(1), row.getString(2), row.getTimestamp(3), - row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8) - ,row.getLong(9)/1000); - } - - @Override - public String select() { - return "select id,ticket,approver,last_notified,user,memo,operation,status,type,WRITETIME(status) from authz.approval"; - } - }; - - /** - * @return the lastNotified - */ - public Date getLast_notified() { - return add.last_notified; - } - /** - * @param lastNotified the lastNotified to set - */ - public void setLastNotified(Date last_notified) { - add.last_notified = last_notified; - } - /** - * @return the status - */ - public String getStatus() { - return add.status; - } - /** - * @param status the status to set - */ - public void setStatus(String status) { - add.status = status; - } - /** - * @return the id - */ - public UUID getId() { - return add.id; - } - /** - * @return the ticket - */ - public UUID getTicket() { - return add.ticket; - } - /** - * @return the approver - */ - public String getApprover() { - return add.approver; - } - /** - * @return the user - */ - public String getUser() { - return add.user; - } - /** - * @return the memo - */ - public String getMemo() { - return add.memo; - } - /** - * @return the operation - */ - public String getOperation() { - return add.operation; - } - /** - * @return the type - */ - public String getType() { - return add.type; - } - public void lapsed() { - add.ticket=null; - add.status="lapsed"; - } - - public String getRole() { - return role; - } - - public String toString() { - return getUser() + ' ' + getMemo(); - } - - public void delayDelete(AuthzTrans trans, ApprovalDAO ad, boolean dryRun, String text) { - if (dryRun) { - trans.info().log(text,"- Would Delete: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); - } else { - Result rv = ad.delete(trans, add, false); - if (rv.isOK()) { - trans.info().log(text,"- Deleted: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); - cache.delayedDelete(this); - } else { - trans.info().log(text,"- Failed to Delete Approval",getId()); - } - } - } - - - public static void resetLocalData() { - cache.resetLocalData(); - } - - public static int sizeForDeletion() { - return cache.cacheSize(); - } - - public static void delayDelete(AuthzTrans noAvg, ApprovalDAO apprDAO, boolean dryRun, List list, String text) { - if (list!=null) { - for (Approval a : list) { - a.delayDelete(noAvg, apprDAO, dryRun,text); - } - } - } - - public static boolean pendingDelete(Approval a) { - return cache.contains(a); - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approver.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approver.java deleted file mode 100644 index 977964f1..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approver.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.HashMap; -import java.util.Map; - -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.org.Organization; - -public class Approver { - public String name; - public Organization org; - public Map userRequests; - - public Approver(String approver, Organization org) { - this.name = approver; - this.org = org; - userRequests = new HashMap<>(); - } - - public void addRequest(String user) { - if (userRequests.get(user) == null) { - userRequests.put(user, 1); - } else { - Integer curCount = userRequests.remove(user); - userRequests.put(user, curCount+1); - } - } - - /** - * @param sb - * @return - */ - public void build(Message msg) { - msg.clear(); - msg.line("You have %d total pending approvals from the following users:", userRequests.size()); - for (Map.Entry entry : userRequests.entrySet()) { - msg.line(" %s (%d)",entry.getKey(),entry.getValue()); - } - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CQLBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CQLBatch.java deleted file mode 100644 index e4d487d6..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CQLBatch.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - */ - -package org.onap.aaf.auth.helpers; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Session; - -public class CQLBatch { - private Session session; - private StringBuilder sb; - private int hasAdded; - - public CQLBatch(Session session) { - this.session = session; - sb = new StringBuilder(); - hasAdded = 0; - } - public StringBuilder begin() { - sb.setLength(0); - sb.append("BEGIN BATCH\n"); - hasAdded = sb.length(); - return sb; - } - - private boolean end() { - if(sb.length()==hasAdded) { - System.out.println("Nothing to Process"); - return false; - } else { - sb.append("APPLY BATCH;\n"); - System.out.println(sb); - return true; - } - } - - public ResultSet execute() { - if(end()) { - return session.execute(sb.toString()); - } else { - return null; - } - } - - public ResultSet execute(boolean dryRun) { - if(dryRun) { - end(); - return null; - } else { - return execute(); - } - - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java deleted file mode 100644 index 1407bdd0..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.List; - -public class CacheChange { - private List removed; - - public CacheChange() { - removed = new ArrayList<>(); - } - - interface Data { - public abstract void expunge(); - } - - public final void delayedDelete(T t) { - removed.add(t); - } - - public final List getRemoved() { - return removed; - } - - public final void resetLocalData() { - if (removed==null || removed.isEmpty()) { - return; - } - for (T t : removed) { - t.expunge(); - } - removed.clear(); - } - - public int cacheSize() { - return removed.size(); - } - - public boolean contains(T t) { - return removed.contains(t); - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java deleted file mode 100644 index a3eb8363..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import com.datastax.driver.core.Row; - -public abstract class Creator { - public abstract T create(Row row); - public abstract String select(); - - public String query(String where) { - StringBuilder sb = new StringBuilder(select()); - if (where!=null) { - sb.append(" WHERE "); - sb.append(where); - } - sb.append(';'); - return sb.toString(); - } - - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java deleted file mode 100644 index ec609488..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java +++ /dev/null @@ -1,325 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeMap; - -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.dao.hl.Question; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Cred { - public static final TreeMap data = new TreeMap<>(); - public static final TreeMap> byNS = new TreeMap<>(); - - public final String id; - public final List instances; - public final String ns; - - public Cred(String id) { - this.id = id; - instances = new ArrayList<>(); - ns=Question.domain2ns(id); - } - - public static class Instance { - public final int type; - public final Date expires,written; - public final Integer other; - - public Instance(int type, Date expires, Integer other, long written) { - this.type = type; - this.expires = expires; - this.other = other; - this.written = new Date(written); - } - - public String toString() { - return expires.toString() + ": " + type; - } - } - - public Date last(final int ... types) { - Date last = null; - for (Instance i : instances) { - if (types.length>0) { // filter by types, if requested - boolean quit = true; - for (int t : types) { - if (t==i.type) { - quit=false; - break; - } - } - if (quit) { - continue; - } - } - if (last==null || i.expires.after(last)) { - last = i.expires; - } - } - return last; - } - - - public Set types() { - Set types = new HashSet<>(); - for (Instance i : instances) { - types.add(i.type); - } - return types; - } - - public static void load(Trans trans, Session session, int ... types ) { - load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred;",types); - - } - - public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) { - load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred WHERE ns='" + ns + "';"); - } - - private static void load(Trans trans, Session session, String query, int ...types) { - - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read Creds", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load Credentials", Env.SUB); - try { - while (iter.hasNext()) { - ++count; - row = iter.next(); - int type = row.getInt(1); - if (types.length>0) { // filter by types, if requested - boolean quit = true; - for (int t : types) { - if (t==type) { - break; - } - } - if (quit) { - continue; - } - } - add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4)); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",count,"creds"); - } - } - - public static void add( - final String id, - final int type, - final Date timestamp, - final int other, - final long written - ) { - Cred cred = data.get(id); - if (cred==null) { - cred = new Cred(id); - data.put(id, cred); - } - cred.instances.add(new Instance(type, timestamp, other, written/1000)); - - List lscd = byNS.get(cred.ns); - if (lscd==null) { - byNS.put(cred.ns, (lscd=new ArrayList<>())); - } - boolean found = false; - for (Cred c : lscd) { - if (c.id.equals(cred.id)) { - found=true; - break; - } - } - if (!found) { - lscd.add(cred); - } - } - - - /** - * Count entries in Cred data. - * Note, as opposed to other methods, need to load the whole cred table for the Types. - * @param numbuckets - * @return - */ - public static CredCount count(int numbuckets) { - CredCount cc = new CredCount(numbuckets); - for (Cred c : data.values()) { - for (Instance ci : c.instances) { - cc.inc(ci.type,ci.written, ci.expires); - } - } - return cc; - } - - public static class CredCount { - public int raw[]; - public int basic_auth[]; - public int basic_auth_256[]; - public int cert[]; - public int x509Added[]; - public int x509Expired[]; - public Date dates[]; - - public CredCount(int numbuckets) { - raw = new int[numbuckets]; - basic_auth = new int[numbuckets]; - basic_auth_256 = new int[numbuckets]; - cert = new int[numbuckets]; - x509Added = new int[numbuckets]; - x509Expired = new int[numbuckets]; - dates = new Date[numbuckets]; - GregorianCalendar gc = new GregorianCalendar(); - dates[0]=gc.getTime(); // now - gc.set(GregorianCalendar.DAY_OF_MONTH, 1); - gc.set(GregorianCalendar.HOUR, 0); - gc.set(GregorianCalendar.MINUTE, 0); - gc.set(GregorianCalendar.SECOND,0); - gc.set(GregorianCalendar.MILLISECOND,0); - gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month - for (int i=1;i row) { - sb.append("DELETE from authz.cred WHERE id='"); - sb.append(row.get(1)); - sb.append("' AND type="); - sb.append(Integer.parseInt(row.get(3))); - // Note: We have to work with long, because Expires is part of Key... can't easily do date. - sb.append(" AND expires=dateof(maxtimeuuid("); - sb.append(row.get(5)); - sb.append("));\n"); - } - - - public String toString() { - StringBuilder sb = new StringBuilder(id); - sb.append('['); - for (Instance i : instances) { - sb.append('{'); - sb.append(i.type); - sb.append(",\""); - sb.append(i.expires); - sb.append("\"}"); - } - sb.append(']'); - return sb.toString(); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - return id.equals(obj); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java deleted file mode 100644 index 8a11479e..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.UUID; - -import org.onap.aaf.auth.dao.cass.FutureDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Future implements CacheChange.Data, Comparable { - public static final Map data = new TreeMap<>(); - public static final Map> byRole = new TreeMap<>(); - - public final FutureDAO.Data fdd; - public final String role; // derived - private static final CacheChange cache = new CacheChange<>(); - - - public final UUID id() { - return fdd.id; - } - - public final String memo() { - return fdd.memo; - } - - public final String target() { - return fdd.target; - } - - public final Date start() { - return fdd.start; - } - - public final Date expires() { - return fdd.expires; - } - - - public Future(UUID id, String memo, String target, Date start, Date expires, ByteBuffer construct) { - fdd = new FutureDAO.Data(); - fdd.id = id; - fdd.memo = memo; - fdd.target = target; - fdd.start = start; - fdd.expires = expires; - fdd.construct = construct; - role = Approval.roleFromMemo(memo); - } - - public static void load(Trans trans, Session session, Creator creator) { - trans.info().log( "query: " + creator.select() ); - ResultSet results; - TimeTaken tt = trans.start("Load Futures", Env.REMOTE); - try { - Statement stmt = new SimpleStatement(creator.select()); - results = session.execute(stmt); - } finally { - tt.done(); - } - - int count = 0; - tt = trans.start("Process Futures", Env.SUB); - try { - for (Row row : results.all()) { - ++count; - Future f = creator.create(row); - data.put(f.fdd.id,f); - if (f.role==null) { - continue; - } - List lf = byRole.get(f.role); - if (lf==null) { - lf = new ArrayList<>(); - byRole.put(f.role,lf); - } - lf.add(f); - - } - } finally { - tt.done(); - trans.info().log("Found",count,"Futures"); - } - } - - public static Creator v2_0_17 = new Creator() { - @Override - public Future create(Row row) { - return new Future(row.getUUID(0),row.getString(1),row.getString(2), - row.getTimestamp(3),row.getTimestamp(4), null); - } - - @Override - public String select() { - return "select id,memo,target,start,expires from authz.future"; - } - }; - - public static Creator withConstruct = new Creator() { - @Override - public String select() { - return "select id,memo,target,start,expires,construct from authz.future"; - } - - @Override - public Future create(Row row) { - return new Future(row.getUUID(0),row.getString(1),row.getString(2), - row.getTimestamp(3),row.getTimestamp(4), row.getBytes(5)); - } - - }; - - public Result delayedDelete(AuthzTrans trans, FutureDAO fd, boolean dryRun, String text) { - Result rv; - if (dryRun) { - trans.info().log(text,"- Would Delete: ",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); - rv = Result.ok(); - } else { - rv = fd.delete(trans, fdd, true); // need to read for undelete - if (rv.isOK()) { - trans.info().log(text, "- Deleted:",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); - cache.delayedDelete(this); - } else { - if (rv.status!=6) { - trans.info().log(text,"- Failed to Delete Future", fdd.id); - } - } - } - return rv; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.helpers.CacheChange.Data#resetLocalData() - */ - @Override - public void expunge() { - data.remove(fdd.id); - if (role!=null) { - List lf = byRole.get(role); - if (lf!=null) { - lf.remove(this); - } - } - } - - @Override - public int compareTo(Future o) { - if (o==null) { - return -1; - } - return fdd.id.compareTo(o.fdd.id); - } - - public static void resetLocalData() { - cache.resetLocalData(); - } - - public static int sizeForDeletion() { - return cache.cacheSize(); - } - - public static boolean pendingDelete(Future f) { - return cache.contains(f); - } - - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java deleted file mode 100644 index cffb55a5..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.nio.ByteBuffer; -import java.util.Iterator; -import java.util.UUID; - -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class History { - public final UUID id; - public final String action; - public final String memo; - public final String reconstruct; - public final String subject; - public final String target; - public final String user; - public final int yr_mon; - - public History(UUID id, String action, String memo, String subject, String target, String user, int yr_mon) { - this.id = id; - this.action = action; - this.memo = memo; - this.reconstruct = null; - this.subject = subject; - this.target = target; - this.user = user; - this.yr_mon = yr_mon; - } - - public History(UUID id, String action, String memo, String reconstruct, String subject, String target, String user, int yr_mon) { - this.id = id; - this.action = action; - this.memo = memo; - this.reconstruct = reconstruct; - this.subject = subject; - this.target = target; - this.user = user; - this.yr_mon = yr_mon; - } - - public static void load(Trans trans, Session session, Creator creator, Loader loader) { - trans.info().log( "query: " + creator.select() ); - TimeTaken tt = trans.start("Read History", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( creator.select() ).setReadTimeoutMillis(240000); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load History", Env.SUB); - try { - while (iter.hasNext()) { - ++count; - row = iter.next(); - loader.exec(creator.create(row)); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",count,"histories"); - } - } - - public String toString() { - return String.format("%s %d %s, %s, %s, %s, %s", - id.toString(), - yr_mon, - user, - target, - action, - subject, - memo); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - return id.equals(obj); - } - - public static Creator sansConstruct = new Creator () { - @Override - public History create(Row row) { - return new History( - row.getUUID(0), - row.getString(1), - row.getString(2), - row.getString(3), - row.getString(4), - row.getString(5), - row.getInt(6)); - } - - @Override - public String select() { - return "SELECT id, action, memo, subject, target, user, yr_mon from authz.history LIMIT 10000000 "; - } - }; - - public static Creator avecConstruct = new Creator () { - private final StringBuilder sb = new StringBuilder(); - - @Override - public History create(Row row) { - ByteBuffer bb = row.getBytes(3); - sb.setLength(0); - - if (bb!=null && bb.hasRemaining()) { - sb.append("0x"); - while (bb.hasRemaining()) { - sb.append(String.format("%02x",bb.get())); - } - bb.flip(); - } - return new History( - row.getUUID(0), - row.getString(1), - row.getString(2), - sb.toString(), - row.getString(4), - row.getString(5), - row.getString(6), - row.getInt(7)); - } - - @Override - public String select() { - return "SELECT id, action, memo, reconstruct, subject, target, user, yr_mon from authz.history LIMIT 10000000 "; - } - }; - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java deleted file mode 100644 index 5fb3e5dc..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Iterator; -import java.util.NoSuchElementException; - -public class InputIterator implements Iterable { - private BufferedReader in; - private final PrintStream out; - private final String prompt, instructions; - - public InputIterator(BufferedReader in, PrintStream out, String prompt, String instructions) { - this.in = in; - this.out = out; - this.prompt = prompt; - this.instructions = instructions; - } - - @Override - public Iterator iterator() { - out.println(instructions); - return new Iterator() { - String input; - @Override - public boolean hasNext() { - out.append(prompt); - try { - input = in.readLine(); - } catch (IOException e) { - input = null; - return false; - } - return input.length()>0; - } - - @Override - public String next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return input; - } - - @Override - public void remove() { - } - }; - } -} - diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Loader.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Loader.java deleted file mode 100644 index 1ec64b7b..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Loader.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -public interface Loader { - public void exec(T t); -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java deleted file mode 100644 index 8eecb656..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.Map; -import java.util.TreeMap; - -import org.onap.aaf.auth.BatchException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class MiscID { - public static final TreeMap data = new TreeMap<>(); - /* - Sample Record - aad890|mj9030|20040902|20120207 - - **** Field Definitions **** - MISCID - AT&T Miscellaneous ID - Non-User ID (Types: Internal Mechanized ID, External Mechanized ID, Datagate ID, Customer ID, Vendor ID, Exchange Mail ID, CLEC ID, Specialized ID, Training ID) - SPONSOR_ATTUID - ATTUID of MiscID Sponsor (Owner) - CREATE_DATE - Date when MiscID was created - LAST_RENEWAL_DATE - Date when MiscID Sponsorship was last renewed - */ - public String id,sponsor,created,renewal; - - private static final String fieldString = "id,created,sponsor,renewal"; - - /** - * Load a Row of Strings (from CSV file). - * - * Be CAREFUL that the Row lists match the Fields above!!! If this changes, change - * 1) This Object - * 2) DB "suits.cql" - * 3) Alter existing Tables - * @param row - * @throws BatchException - * @throws IllegalAccessException - * @throws IllegalArgumentException - */ - public void set(String row []) throws BatchException { - if (row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} - id = row[0]; - sponsor = row[1]; - created = row[2]; - renewal = row[3]; - } - - public void set(Row row) { - id = row.getString(0); - sponsor = row.getString(1); - created = row.getString(2); - renewal = row.getString(3); - } - - - public static void load(Trans trans, Session session ) { - load(trans, session,"SELECT " + fieldString + " FROM authz.miscid;",data); - } - - public static void load(Trans trans, Session session, Map map ) { - load(trans, session,"SELECT " + fieldString + " FROM authz.miscid;",map); - } - - public static void loadOne(Trans trans, Session session, String id ) { - load(trans, session,"SELECT " + fieldString + " FROM authz.miscid WHERE id ='" + id + "';", data); - } - - public static void load(Trans trans, Session session, String query, Map map) { - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read MiscID", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - try { - tt = trans.start("Load Map", Env.SUB); - try { - for ( Row row : results.all()) { - MiscID miscID = new MiscID(); - miscID.set(row); - data.put(miscID.id,miscID); - ++count; - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",count,"miscID records"); - } - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj!=null && obj instanceof MiscID) { - return id.equals(((MiscID)obj).id); - } - return false; - } - - public StringBuilder insertStmt() throws IllegalArgumentException, IllegalAccessException { - StringBuilder sb = new StringBuilder("INSERT INTO authz.miscid ("); - sb.append(fieldString); - sb.append(") VALUES ('"); - sb.append(id); - sb.append("','"); - sb.append(sponsor); - sb.append("','"); - sb.append(created); - sb.append("','"); - sb.append(renewal); - sb.append("')"); - return sb; - } - - public StringBuilder updateStmt(MiscID source) { - StringBuilder sb = null; - if (id.equals(source.id)) { - sb = addField(sb,"sponser",sponsor,source.sponsor); - sb = addField(sb,"created",created,source.created); - sb = addField(sb,"renewal",renewal,source.renewal); - } - if (sb!=null) { - sb.append(" WHERE id='"); - sb.append(id); - sb.append('\''); - } - return sb; - } - - private StringBuilder addField(StringBuilder sb, String name, String a, String b) { - if (!a.equals(b)) { - if (sb==null) { - sb = new StringBuilder("UPDATE authz.miscid SET "); - } else { - sb.append(','); - } - sb.append(name); - sb.append("='"); - sb.append(b); - sb.append('\''); - } - return sb; - } - - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java deleted file mode 100644 index e15a6bc2..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintStream; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; - -import org.onap.aaf.misc.env.util.Split; - -import java.util.Set; -import java.util.TreeMap; - -public class MonthData { - public final Map> data = new TreeMap<>(); - private File f; - - public MonthData(String env) throws IOException { - f = new File("Monthly"+env+".dat"); - - if (f.exists()) { - BufferedReader br = new BufferedReader(new FileReader(f)); - try { - String line; - String[] split; - while ((line=br.readLine())!=null) { - if (!line.startsWith("#")) { - split = Split.split(',', line); - if (split.length==5) { - add(Integer.parseInt(split[0]),split[1], - Integer.parseInt(split[2]), - Integer.parseInt(split[3]), - Integer.parseInt(split[4]) - ); - } - } - } - } finally { - br.close(); - } - } - } - - public void add(int yr_mon, String target, long total, long adds, long drops) { - Set row = data.get(yr_mon); - if (row==null) { - data.put(yr_mon, (row=new HashSet<>())); - } - row.add(new Row(target,total,adds,drops)); - } - - public boolean notExists(int yr_mon) { - return data.get(yr_mon)==null; - } - - public static class Row implements Comparable { - public final String target; - public final long total; - public final long adds; - public final long drops; - - public Row(String t, long it, long a, long d) { - target = t; - total = it; - adds = a; - drops = d; - } - - @Override - public int compareTo(Row o) { - return target.compareTo(o.target); - } - - public String toString() { - return target + '|' + total + '|' + drops + '|' + adds; - } - } - - public void write() throws IOException { - if (f.exists()) { - File bu = new File(f.getName()+".bak"); - f.renameTo(bu); - } - PrintStream ps = new PrintStream(f); - try { - for ( Entry> rows : data.entrySet()) { - for (Row row : rows.getValue()) { - ps.printf("%d,%s,%d,%d,%d\n",rows.getKey(),row.target,row.total,row.adds,row.drops); - } - } - } finally { - ps.close(); - } - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java deleted file mode 100644 index 5692d116..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.Iterator; -import java.util.Map; -import java.util.TreeMap; - -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class NS implements Comparable { - public final static Map data = new TreeMap<>(); - - public final String name, description, parent; - public final int scope,type; - - public NS(String name, String description, String parent, int type, int scope) { - this.name = name; - this.description = description; - this.parent = parent; - this.scope = scope; - this.type = type; - } - - public static void load(Trans trans, Session session, Creator creator) { - load(trans,session, - "select name, description, parent, type, scope from authz.ns;" - ,creator); - } - - public static void loadOne(Trans trans, Session session, Creator creator, String ns) { - load(trans,session, - ("select name, description, parent, type, scope from authz.ns WHERE name='"+ns+"';") - ,creator - ); - } - - private static void load(Trans trans, Session session, String query, Creator creator) { - trans.info().log( "query: " + query ); - ResultSet results; - TimeTaken tt; - - tt = trans.start("Read Namespaces", Env.REMOTE); - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - - - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load Namespaces", Env.SUB); - try { - while (iter.hasNext()) { - row = iter.next(); - NS ns = creator.create(row); - data.put(ns.name,ns); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",data.size(),"Namespaces"); - } - - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.ns LIMIT 1000000;"; - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); - results = session.execute(stmt); - return results.one().getLong(0); - } finally { - tt.done(); - } - } - - public String toString() { - return name; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return name.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - return name.equals(obj); - } - - @Override - public int compareTo(NS o) { - return name.compareTo(o.name); - } - - public static class NSSplit { - public String ns; - public String other; - public NSSplit(String s, int dot) { - ns = s.substring(0,dot); - other = s.substring(dot+1); - } - } - public static NSSplit deriveParent(String dotted) { - if (dotted==null)return null; - for (int idx = dotted.lastIndexOf('.');idx>=0; idx=dotted.lastIndexOf('.',idx-1)) { - if (data.get(dotted.substring(0, idx))!=null) { - return new NSSplit(dotted,idx); - } - } - return null; - } - - public static Creator v2_0_11 = new Creator () { - @Override - public NS create(Row row) { - return new NS(row.getString(0),row.getString(1), row.getString(2),row.getInt(3),row.getInt(4)); - } - - @Override - public String select() { - return "SELECT name, description, parent, type, scope FROM authz.ns "; - } - }; - - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java deleted file mode 100644 index b178c377..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TreeMap; - -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Notification { - public enum TYPE { - OA("Owner Approval",1),SA("Supervisor Approval",2),CN("Credential Expiration",20); - - private String desc; - private int type; - - private TYPE(String desc,int type) { - this.desc = desc; - this.type = type; - } - - public String desc() { - return desc; - } - - public int idx() { - return type; - } - - public static TYPE get(int idx) { - for (TYPE nt : TYPE.values()) { - if (idx==nt.type) { - return nt; - } - } - return null; - } - } - - - public static final TreeMap> data = new TreeMap<>(); - public static final Date now = new Date(); - - public final String user; - public final TYPE type; - public Date last; - public int checksum; - public Message msg; - private int current; - public Organization org; - public int count; - - private Notification(String user, TYPE nt, Date last, int checksum) { - this.user = user; - this.type = nt; - this.last = last; - this.checksum = checksum; - current = 0; - count = 0; - } - - public static void load(Trans trans, Session session, Creator creator ) { - trans.info().log( "query: " + creator.select() ); - TimeTaken tt = trans.start("Load Notify", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement(creator.select()); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - tt = trans.start("Process Notify", Env.SUB); - - try { - for (Row row : results.all()) { - ++count; - try { - Notification not = creator.create(row); - List ln = data.get(not.user); - if (ln==null) { - ln = new ArrayList<>(); - data.put(not.user, ln); - } - ln.add(not); - } finally { - tt.done(); - } - } - } finally { - tt.done(); - trans.info().log("Found",count,"Notify Records"); - } - } - - public static Notification get(String user, TYPE type) { - List ln = data.get(user); - if (ln!=null) { - for (Notification n : ln) { - if (type.equals(n.type)) { - return n; - } - } - } - return null; - } - - public static Notification create(String user, TYPE type) { - return new Notification(user,type,null,0); - } - - public static Creator v2_0_18 = new Creator() { - @Override - public Notification create(Row row) { - int idx =row.getInt(1); - TYPE type = TYPE.get(idx); - if (type==null) { - return null; - } - return new Notification(row.getString(0), type, row.getTimestamp(2), row.getInt(3)); - } - - @Override - public String select() { - return "SELECT user,type,last,checksum FROM authz.notify LIMIT 100000"; - } - }; - - - public void set(Message msg) { - this.msg = msg; - } - - public int checksum() { - if (msg==null) { - current=0; - } else if (current==0) { - for (String l : msg.lines) { - for (byte b : l.getBytes()) { - current+=b; - } - } - } - return current; - } - - public boolean update(AuthzTrans trans, Session session, boolean dryRun) { - checksum(); - if (last==null || current==0 || current!=checksum) { - last = now; - current = checksum(); - String update = "UPDATE authz.notify SET " + - "last = '" + Chrono.utcStamp(last) + - "', checksum=" + - current + - " WHERE user='" + - user + - "' AND type=" + - type.idx() + - ";"; - if (dryRun) { - trans.info().log("Would",update); - } else { - session.execute(update); - } - return true; - } - return false; - } - - public String toString() { - return "\"" + user + "\",\"" + type.name() + "\",\"" - + Chrono.dateTime(last)+ "\", " + checksum; - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java deleted file mode 100644 index a3354f38..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class NsAttrib { - public static final List data = new ArrayList<>(); - public static final SortedMap> byKey = new TreeMap<>(); - public static final SortedMap> byNS = new TreeMap<>(); - - public final String ns; - public final String key; - public final String value; - public static Creator v2_0_11 = new Creator() { - @Override - public NsAttrib create(Row row) { - return new NsAttrib(row.getString(0), row.getString(1), row.getString(2)); - } - - @Override - public String select() { - return "select ns,key,value from authz.ns_attrib"; - } - }; - - public NsAttrib(String ns, String key, String value) { - this.ns = ns; - this.key = key; - this.value = value; - } - - public static void load(Trans trans, Session session, Creator creator ) { - trans.info().log( "query: " + creator.select() ); - ResultSet results; - TimeTaken tt = trans.start("Load NsAttributes", Env.REMOTE); - try { - Statement stmt = new SimpleStatement(creator.select()); - results = session.execute(stmt); - } finally { - tt.done(); - } - int count = 0; - tt = trans.start("Process NsAttributes", Env.SUB); - - try { - for (Row row : results.all()) { - ++count; - NsAttrib ur = creator.create(row); - data.add(ur); - - List lna = byKey.get(ur.key); - if (lna==null) { - lna = new ArrayList<>(); - byKey.put(ur.key, lna); - } - lna.add(ur); - - lna = byNS.get(ur.ns); - if (lna==null) { - lna = new ArrayList<>(); - byNS.put(ur.ns, lna); - } - lna.add(ur); - } - } finally { - tt.done(); - trans.info().log("Found",count,"NS Attributes"); - } - } - - public String toString() { - return '"' + ns + "\",\"" + key + "\",\"" + value +'"'; - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java deleted file mode 100644 index ee588f31..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeMap; - -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Perm implements Comparable { - public static final TreeMap> data = new TreeMap<>(); - public static final TreeMap keys = new TreeMap<>(); - private static List deletePerms = new ArrayList<>(); - - public final String ns, type, instance, action,description; - private String fullType = null, fullPerm = null, encode = null; - public final Set roles; - - public String encode() { - if (encode == null) { - encode = ns + '|' + type + '|' + instance + '|' + action; - } - return encode; - } - - public String fullType() { - if (fullType==null) { - fullType = ns + '.' + type; - } - return fullType; - } - - public String fullPerm() { - if (fullPerm==null) { - fullPerm = ns + '.' + type + '|' + instance + '|' + action; - } - return fullPerm; - } - - public Perm(String ns, String type, String instance, String action, String description, Set roles) { - this.ns = ns; - this.type = type; - this.instance = instance; - this.action = action; - this.description = description; - // 2.0.11 -// this.full = encode();//ns+'.'+type+'|'+instance+'|'+action; - this.roles = roles; - } - - public static void load(Trans trans, Session session) { - load(trans, session, "select ns, type, instance, action, description, roles from authz.perm;"); - } - - public static void loadOneNS(Trans trans, Session session, String ns) { - load(trans, session, "select ns, type, instance, action, description, roles from authz.perm WHERE ns='" + ns + "';"); - - } - - private static void load(Trans trans, Session session, String query) { - // - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read Perms", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load Perms", Env.SUB); - try { - while (iter.hasNext()) { - row = iter.next(); - Perm pk = new Perm( - row.getString(0),row.getString(1),row.getString(2), - row.getString(3), row.getString(4), row.getSet(5,String.class)); - keys.put(pk.encode(), pk); - data.put(pk,pk.roles); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",data.size(),"perms"); - } - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.perm LIMIT 1000000;"; - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); - results = session.execute(stmt); - return results.one().getLong(0); - } finally { - tt.done(); - } - } - - public String toString() { - return encode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return encode().hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - return encode().equals(obj); - } - - @Override - public int compareTo(Perm o) { - return encode().compareTo(o.encode()); - } - - public static void stageRemove(Perm p) { - deletePerms.add(p); - } - - public static void executeRemove() { - for (Perm p : deletePerms) { - keys.remove(p.encode); - data.remove(p); - } - deletePerms.clear(); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java deleted file mode 100644 index 04a5dceb..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java +++ /dev/null @@ -1,175 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.TreeMap; - -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class Role implements Comparable { - public static final TreeMap> data = new TreeMap<>(); - public static final TreeMap keys = new TreeMap<>(); - public static final TreeMap byName = new TreeMap<>(); - private static List deleteRoles = new ArrayList<>(); - - public final String ns, name, description; - private String full, encode; - public final Set perms; - - public Role(String full) { - ns = name = description = ""; - this.full = full; - perms = new HashSet<>(); - } - - public Role(String ns, String name, String description,Set perms) { - this.ns = ns; - this.name = name; - this.description = description; - this.full = null; - this.encode = null; - this.perms = perms; - } - - public String encode() { - if (encode==null) { - encode = ns + '|' + name; - } - return encode; - } - - public String fullName() { - if (full==null) { - full = ns + '.' + name; - } - return full; - } - - public static void load(Trans trans, Session session ) { - load(trans,session,"select ns, name, description, perms from authz.role;"); - } - - public static void loadOneNS(Trans trans, Session session, String ns ) { - load(trans,session,"select ns, name, description, perms from authz.role WHERE ns='" + ns + "';"); - } - - private static void load(Trans trans, Session session, String query) { - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read Roles", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load Roles", Env.SUB); - try { - while (iter.hasNext()) { - row = iter.next(); - Role rk =new Role(row.getString(0),row.getString(1), row.getString(2),row.getSet(3,String.class)); - keys.put(rk.encode(), rk); - data.put(rk,rk.perms); - byName.put(rk.fullName(), rk); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",data.size(),"roles"); - } - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.role LIMIT 1000000;"; - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); - results = session.execute(stmt); - return results.one().getLong(0); - } finally { - tt.done(); - } - } - - public String toString() { - return encode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return encode().hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - return encode().equals(obj); - } - - @Override - public int compareTo(Role o) { - return encode().compareTo(o.encode()); - } - - public static String fullName(String role) { - return role.replace('|', '.'); - } - - public static void stageRemove(Role r) { - deleteRoles.add(r); - } - - public static void executeRemove() { - for (Role p : deleteRoles) { - keys.remove(p.encode); - data.remove(p); - } - deleteRoles.clear(); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java deleted file mode 100644 index d9e6bed3..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java +++ /dev/null @@ -1,322 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.onap.aaf.auth.actions.URDelete; -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class UserRole implements Cloneable, CacheChange.Data { - - private static final String SEPARATOR = "\",\""; - - // CACHE Calling - private static final String LOG_FMT = "%s UserRole - %s: %s-%s (%s, %s) expiring %s"; - private static final String REPLAY_FMT = "%s|%s|%s|%s|%s\n"; - private static final String DELETE_FMT = "# %s\n"+ REPLAY_FMT; - - private static final List data = new ArrayList<>(); - private static final SortedMap> byUser = new TreeMap<>(); - private static final SortedMap> byRole = new TreeMap<>(); - private static final CacheChange cache = new CacheChange<>(); - private static PrintStream urDelete = System.out; - private static PrintStream urRecover = System.err; - private static int totalLoaded; - private int deleted; - private Data urdd; - - public static final Creator v2_0_11 = new Creator() { - @Override - public UserRole create(Row row) { - return new UserRole(row.getString(0), row.getString(1), row.getString(2),row.getString(3),row.getTimestamp(4)); - } - - @Override - public String select() { - return "select user,role,ns,rname,expires from authz.user_role"; - } - }; - - public UserRole(String user, String ns, String rname, Date expires) { - urdd = new UserRoleDAO.Data(); - urdd.user = user; - urdd.role = ns + '.' + rname; - urdd.ns = ns; - urdd.rname = rname; - urdd.expires = expires; - } - - public UserRole(String user, String role, String ns, String rname, Date expires) { - urdd = new UserRoleDAO.Data(); - urdd.user = user; - urdd.role = role; - urdd.ns = ns; - urdd.rname = rname; - urdd.expires = expires; - } - - public static List getData() { - return data; - } - - public static SortedMap> getByUser() { - return byUser; - } - - public static SortedMap> getByRole() { - return byRole; - } - - public static void load(Trans trans, Session session, Creator creator, Visitor visitor ) { - load(trans,session,creator,null,visitor); - } - - public static void loadOneRole(Trans trans, Session session, Creator creator, String role, Visitor visitor) { - load(trans,session,creator,"role='" + role +"' ALLOW FILTERING;",visitor); - } - - public static void loadOneUser(Trans trans, Session session, Creator creator, String user, Visitor visitor ) { - load(trans,session,creator,"role='"+ user +"';",visitor); - } - - private static void load(Trans trans, Session session, Creator creator, String where, Visitor visitor) { - String query = creator.query(where); - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read UserRoles", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - try { - tt = trans.start("Load UserRole", Env.SUB); - try { - iterateResults(creator, results.iterator(), visitor); - } finally { - tt.done(); - } - } finally { - trans.info().log("Loaded",totalLoaded,"UserRoles"); - } - } - - private static void iterateResults(Creator creator, Iterator iter, Visitor visit ) { - Row row; - while (iter.hasNext()) { - ++totalLoaded; - row = iter.next(); - UserRole ur = creator.create(row); - visit.visit(ur); - } - } - - public static class DataLoadVisitor implements Visitor { - @Override - public void visit(UserRole ur) { - data.add(ur); - - List lur = byUser.get(ur.urdd.user); - if (lur==null) { - lur = new ArrayList<>(); - byUser.put(ur.urdd.user, lur); - } - lur.add(ur); - - lur = byRole.get(ur.urdd.role); - if (lur==null) { - lur = new ArrayList<>(); - byRole.put(ur.urdd.role, lur); - } - lur.add(ur); - } - } - - public int totalLoaded() { - return totalLoaded; - } - - public int deleted() { - return deleted; - } - - @Override - public void expunge() { - data.remove(this); - - List lur = byUser.get(urdd.user); - if (lur!=null) { - lur.remove(this); - } - - lur = byRole.get(urdd.role); - if (lur!=null) { - lur.remove(this); - } - } - - public static void setDeleteStream(PrintStream ds) { - urDelete = ds; - } - - public static void setRecoverStream(PrintStream ds) { - urRecover = ds; - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.user_role LIMIT 1000000;"; - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); - results = session.execute(stmt); - return results.one().getLong(0); - } finally { - tt.done(); - } - } - - public UserRoleDAO.Data urdd() { - return urdd; - } - - public String user() { - return urdd.user; - } - - public String role() { - return urdd.role; - } - - public String ns() { - return urdd.ns; - } - - public String rname() { - return urdd.rname; - } - - public Date expires() { - return urdd.expires; - } - - public void expires(Date time) { - urdd.expires = time; - } - - public String toString() { - return "\"" + urdd.user + SEPARATOR + urdd.role + SEPARATOR + urdd.ns + SEPARATOR + urdd.rname + SEPARATOR - + Chrono.dateOnlyStamp(urdd.expires); - } - - public static UserRole get(String u, String r) { - List lur = byUser.get(u); - if (lur!=null) { - for (UserRole ur : lur) { - - if (ur.urdd.role.equals(r)) { - return ur; - } - } - } - return null; - } - - // SAFETY - DO NOT DELETE USER ROLES DIRECTLY FROM BATCH FILES!!! - // We write to a file, and validate. If the size is iffy, we email Support - public void delayDelete(AuthzTrans trans, String text, boolean dryRun) { - String dt = Chrono.dateTime(urdd.expires); - if (dryRun) { - trans.info().printf(LOG_FMT,text,"Would Delete",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); - } else { - trans.info().printf(LOG_FMT,text,"Staged Deletion",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); - } - urDelete.printf(DELETE_FMT,text,urdd.user,urdd.role,dt,urdd.ns,urdd.rname); - urRecover.printf(REPLAY_FMT,urdd.user,urdd.role,dt,urdd.ns,urdd.rname); - - cache.delayedDelete(this); - ++deleted; - } - - - /** - * Calls expunge() for all deleteCached entries - */ - public static void resetLocalData() { - cache.resetLocalData(); - } - - public static int sizeForDeletion() { - return cache.cacheSize(); - } - - public static boolean pendingDelete(UserRole ur) { - return cache.contains(ur); - } - - public static void actuateDeletionNow(AuthzTrans trans, URDelete directDel) { - for (UserRole ur : cache.getRemoved()) { - directDel.exec(trans, ur, "Actuating UserRole Deletion"); - } - cache.getRemoved().clear(); - cache.resetLocalData(); - } - - public void row(final CSV.Writer csvw) { - csvw.row("ur",user(),ns(),rname(),Chrono.dateOnlyStamp(expires())); - } - - public static void row(StringBuilder sb, List row) { - sb.append("DELETE from authz.user_role WHERE user='"); - sb.append(row.get(1)); - sb.append("' AND role='"); - sb.append(row.get(2)); - sb.append('.'); - sb.append(row.get(3)); - sb.append("';\n"); - } - - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Visitor.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Visitor.java deleted file mode 100644 index 1eb9ffec..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Visitor.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - */ - -package org.onap.aaf.auth.helpers; - -public interface Visitor { - void visit(T t); -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/X509.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/X509.java deleted file mode 100644 index 95fe3c0e..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/X509.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.security.cert.X509Certificate; -import java.util.Iterator; -import java.util.List; - -import org.onap.aaf.cadi.Hash; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; -import org.onap.aaf.misc.env.util.Chrono; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; - -public class X509 { - public final String ca,id,x500,x509; - public ByteBuffer serial; - - public X509(String ca, String id, String x500, String x509, ByteBuffer serial) { - this.ca = ca; - this.id = id; - this.x500 = x500; - this.x509 = x509; - this.serial = serial; - } - - - public static void load(Trans trans, Session session, Visitor visitor) { - load(trans,session,"select ca, id, x500, x509, serial from authz.x509;", visitor); - } - - private static void load(Trans trans, Session session, String query, Visitor visitor) { - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Read Roles", Env.REMOTE); - - ResultSet results; - try { - Statement stmt = new SimpleStatement( query ); - results = session.execute(stmt); - } finally { - tt.done(); - } - - int count = 0; - try { - Iterator iter = results.iterator(); - Row row; - tt = trans.start("Load X509s", Env.SUB); - try { - while (iter.hasNext()) { - ++count; - row = iter.next(); - visitor.visit(new X509(row.getString(0),row.getString(1), row.getString(2),row.getString(3),row.getBytes(4))); - } - } finally { - tt.done(); - } - } finally { - trans.info().log("Found",count,"X509 Certificates"); - } - } - - public static long count(Trans trans, Session session) { - String query = "select count(*) from authz.x509 LIMIT 1000000;"; - trans.info().log( "query: " + query ); - TimeTaken tt = trans.start("Count x509s", Env.REMOTE); - ResultSet results; - try { - Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000); - results = session.execute(stmt); - return results.one().getLong(0); - } finally { - tt.done(); - } - } - - - public void row(CSV.Writer cw, X509Certificate x509Cert) throws IOException { - cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500); - } - - - public static void row(StringBuilder sb, List row) throws IOException { - sb.append("DELETE from authz.x509 WHERE ca='"); - sb.append(row.get(1)); - sb.append("' AND serial="); - sb.append(row.get(2)); - sb.append(";\n"); - } - -} \ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/Expiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/Expiring.java deleted file mode 100644 index 289da58e..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/Expiring.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.reports; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Cred; -import org.onap.aaf.auth.helpers.Cred.Instance; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.helpers.Visitor; -import org.onap.aaf.auth.helpers.X509; -import org.onap.aaf.auth.org.ExpireRange; -import org.onap.aaf.auth.org.ExpireRange.Range; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.cadi.configure.Factory; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.util.Chrono; - - -public class Expiring extends Batch { - - private static final String CSV = ".csv"; - private static final String INFO = "info"; - private static final String EXPIRED_OWNERS = "ExpiredOwners"; - private int minOwners; - private Map writerList; - private File logDir; - private ExpireRange expireRange; - private Date deleteDate; - - public Expiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - - // Load Cred. We don't follow Visitor, because we have to gather up everything into Identity Anyway - Cred.load(trans, session); - UserRole.load(trans, session, UserRole.v2_0_11, new UserRole.DataLoadVisitor()); - - minOwners=1; - - // Create Intermediate Output - writerList = new HashMap<>(); - logDir = new File(logDir()); - logDir.mkdirs(); - - expireRange = new ExpireRange(trans.env().access()); - String sdate = Chrono.dateOnlyStamp(expireRange.now); - for( List lr : expireRange.ranges.values()) { - for(Range r : lr ) { - if(writerList.get(r.name())==null) { - File file = new File(logDir,r.name() + sdate +CSV); - CSV csv = new CSV(file); - CSV.Writer cw = csv.writer(false); - cw.row(INFO,r.name(),Chrono.dateOnlyStamp(expireRange.now),r.reportingLevel()); - writerList.put(r.name(),cw); - if("Delete".equals(r.name())) { - deleteDate = r.getStart(); - } - } - } - } - - } finally { - tt0.done(); - } - } - - @Override - protected void run(AuthzTrans trans) { - try { - File file = new File(logDir, EXPIRED_OWNERS + Chrono.dateOnlyStamp(expireRange.now) + CSV); - final CSV ownerCSV = new CSV(file); - - Map> owners = new TreeMap>(); - trans.info().log("Process UserRoles"); - UserRole.load(trans, session, UserRole.v2_0_11, new Visitor() { - @Override - public void visit(UserRole ur) { - // Cannot just delete owners, unless there is at least one left. Process later - if ("owner".equals(ur.rname())) { - Set urs = owners.get(ur.role()); - if (urs == null) { - urs = new HashSet(); - owners.put(ur.role(), urs); - } - urs.add(ur); - } else { - writeAnalysis(trans,ur); - } - } - }); - - // Now Process Owners, one owner Role at a time, ensuring one is left, - // preferably - // a good one. If so, process the others as normal. Otherwise, write - // ExpiredOwners - // report - if (!owners.values().isEmpty()) { - // Lazy Create file - CSV.Writer expOwner = null; - try { - for (Set sur : owners.values()) { - int goodOwners = 0; - for (UserRole ur : sur) { - if (ur.expires().after(expireRange.now)) { - ++goodOwners; - } - } - - for (UserRole ur : sur) { - if (goodOwners >= minOwners) { - writeAnalysis(trans, ur); - } else { - if (expOwner == null) { - expOwner = ownerCSV.writer(); - expOwner.row(INFO,EXPIRED_OWNERS,Chrono.dateOnlyStamp(expireRange.now),2); - } - expOwner.row("owner",ur.role(), ur.user(), Chrono.dateOnlyStamp(ur.expires())); - } - } - } - } finally { - if(expOwner!=null) { - expOwner.close(); - } - } - } - - trans.info().log("Checking for Expired Credentials"); - - for (Cred cred : Cred.data.values()) { - List linst = cred.instances; - if(linst!=null) { - Instance lastBath = null; - for(Instance inst : linst) { - // Special Behavior: only eval the LAST Instance - if (inst.type == CredDAO.BASIC_AUTH || inst.type == CredDAO.BASIC_AUTH_SHA256) { - if(deleteDate!=null && inst.expires.before(deleteDate)) { - writeAnalysis(trans, cred, inst); // will go to Delete - } else if(lastBath==null || lastBath.expires.before(inst.expires)) { - lastBath = inst; - } - } else { - writeAnalysis(trans, cred, inst); - } - } - if(lastBath!=null) { - writeAnalysis(trans, cred, lastBath); - } - } - } - - trans.info().log("Checking for Expired X509s"); - X509.load(trans, session, new Visitor() { - @Override - public void visit(X509 x509) { - try { - for(Certificate cert : Factory.toX509Certificate(x509.x509)) { - writeAnalysis(trans, x509, (X509Certificate)cert); - } - } catch (CertificateException | IOException e) { - trans.error().log(e, "Error Decrypting X509"); - } - - } - }); - } catch (FileNotFoundException e) { - trans.info().log(e); - } - } - - - private void writeAnalysis(AuthzTrans trans, UserRole ur) { - Range r = expireRange.getRange("ur", ur.expires()); - if(r!=null) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - ur.row(cw); - } - } - } - - private void writeAnalysis(AuthzTrans trans, Cred cred, Instance inst) { - if(cred!=null && inst!=null) { - Range r = expireRange.getRange("cred", inst.expires); - if(r!=null) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - cred.row(cw,inst); - } - } - } - } - - private void writeAnalysis(AuthzTrans trans, X509 x509, X509Certificate x509Cert) throws IOException { - Range r = expireRange.getRange("x509", x509Cert.getNotAfter()); - if(r!=null) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - x509.row(cw,x509Cert); - } - } - } - - /* - private String[] contacts(final AuthzTrans trans, final String ns, final int levels) { - List owners = UserRole.getByRole().get(ns+".owner"); - List current = new ArrayList<>(); - for(UserRole ur : owners) { - if(expireRange.now.before(ur.expires())) { - current.add(ur); - } - } - if(current.isEmpty()) { - trans.warn().log(ns,"has no current owners"); - current = owners; - } - - List email = new ArrayList<>(); - for(UserRole ur : current) { - Identity id; - int i=0; - boolean go = true; - try { - id = org.getIdentity(trans, ur.user()); - do { - if(id!=null) { - email.add(id.email()); - if(i la : Approval.byUser.values()) { - for (Approval a : la ) { - memo = a.getMemo(); - if (memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { - String role = a.getRole(); - if (role!=null) { - UserRole ur = UserRole.get(a.getUser(), a.getRole()); - Future f=null; - if (ur!=null) { - if (ur.expires().after(future)) { // no need for Approval anymore - a.delayDelete(noAvg, apprDAO, dryRun, "User Role already Extended"); - UUID tkt = a.getTicket(); - if (tkt!=null && Future.data.containsKey(tkt)) { - f = Future.data.get(a.getTicket()); - } - } - } else { - a.delayDelete(noAvg, apprDAO, dryRun, "User Role does not exist"); - UUID tkt = a.getTicket(); - if (tkt !=null && Future.data.containsKey(tkt)) { - f = Future.data.get(a.getTicket()); - } - } - if (f!=null) { - f.delayedDelete(noAvg, futureDAO, dryRun, "Approvals removed"); - } - } - } - } - } - try { - trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); - Future.resetLocalData(); - Approval.resetLocalData(); - } catch (Exception t) { - t.printStackTrace(); - } - - // Run for Expired Futures - trans.info().log("Checking for Expired Approval/Futures"); - tt = trans.start("Delete old Futures", Env.REMOTE); - trans.info().log("### Running Future Execution on ",Future.data.size(), "Items"); - // Execute any Futures waiting - for (Future f : Future.data.values()) { - if (f.memo().contains("Re-Approval") || f.memo().contains("Re-Validate")) { - List la = Approval.byTicket.get(f.id()); - if (la!=null) { - Result ruf = urFutureApproveExec.exec(noAvg,la,f); - if (ruf.isOK()) { - switch(ruf.value) { - case P: - break; - case E: - case D: - case L: - f.delayedDelete(noAvg, futureDAO, dryRun,OP_STATUS.L.desc()); - Approval.delayDelete(noAvg, apprDAO, dryRun, la,OP_STATUS.L.desc()); - break; - } - } - } - } - } - try { - trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); - Future.resetLocalData(); - Approval.resetLocalData(); - } catch (Exception t) { - t.printStackTrace(); - } - - - trans.info().log("### Remove Expired on ",Future.data.size(), "Items, or premature ones"); - // Remove Expired - String expiredBeforeNow = "Expired before " + tooLate; - String expiredAfterFuture = "Expired after " + future; - try { - for (Future f : Future.data.values()) { - if (f.expires().before(tooLate)) { - f.delayedDelete(noAvg,futureDAO,dryRun, expiredBeforeNow); - Approval.delayDelete(noAvg, apprDAO, dryRun, Approval.byTicket.get(f.id()), expiredBeforeNow); - } else if (f.expires().after(future)) { - f.delayedDelete(noAvg,futureDAO,dryRun, expiredAfterFuture); - Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), expiredAfterFuture); - } - } - try { - trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); - Future.resetLocalData(); - Approval.resetLocalData(); - } catch (Exception t) { - t.printStackTrace(); - } - } finally { - tt.done(); - } - - trans.info().log("### Checking Approvals valid (",Approval.byApprover.size(),"Items)"); - // Make sure users of Approvals are still valid - for (List lapp : Approval.byTicket.values()) { - for (Approval app : lapp) { - Future f; - if (app.getTicket()==null) { - f = null; - } else { - f = Future.data.get(app.getTicket()); - if (Future.pendingDelete(f)) { - f=null; - } - } - String msg; - if (f!=null && app.getRole()!=null && Role.byName.get(app.getRole())==null) { - f.delayedDelete(noAvg,futureDAO,dryRun,msg="Role '" + app.getRole() + "' no longer exists"); - Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); - continue; - } - - switch(app.getStatus()) { - case "pending": - if (f==null) { - app.delayDelete(noAvg,apprDAO, isDryRun(), "ticketDeleted"); - continue; - } - switch(app.getType()) { - case "owner": - boolean anOwner=false; - String approle = app.getRole(); - if (approle!=null) { - Role role = Role.byName.get(approle); - if (role==null) { - app.delayDelete(noAvg, apprDAO, dryRun, "Role No Longer Exists"); - continue; - } else { - // Make sure Owner Role exists - String owner = role.ns + ".owner"; - if (Role.byName.containsKey(owner)) { - List lur = UserRole.getByRole().get(owner); - if (lur != null) { - for (UserRole ur : lur) { - if (ur.user().equals(app.getApprover())) { - anOwner = true; - break; - } - } - } - } - } - if (!anOwner) { - app.delayDelete(noAvg, apprDAO, dryRun, "No longer Owner"); - } - - } - break; - case "supervisor": - try { - Identity identity = org.getIdentity(noAvg, app.getUser()); - if (identity==null) { - if (f!=null) { - f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getUser() + " is no longer associated with " + org.getName()); - Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); - } - } else { - if (!app.getApprover().equals(identity.responsibleTo().fullID())) { - if (f!=null) { - f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getApprover() + " is no longer a Supervisor of " + app.getUser()); - Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); - } - } - } - } catch (OrganizationException e) { - e.printStackTrace(); - } - break; - } - break; - } - } - } - try { - trans.info().log("### Removed",Future.sizeForDeletion(),"Future and",Approval.sizeForDeletion(),"Approvals"); - Future.resetLocalData(); - Approval.resetLocalData(); - } catch (Exception t) { - t.printStackTrace(); - } - - int count = 0, deleted=0, delayedURDeletes = 0; - - // Run for User Roles - trans.info().log("Checking for Expired User Roles"); - try { - for (UserRole ur : UserRole.getData()) { - if (org.getIdentity(noAvg, ur.user())==null) { // if not part of Organization; - if (isSpecial(ur.user())) { - trans.info().log(ur.user(),"is not part of organization, but may not be deleted"); - } else { - ur.delayDelete(noAvg, "Not Part of Organization", dryRun); - ++deleted; - ++delayedURDeletes; - } - } else { - if (NS.data.get(ur.ns())==null) { - ur.delayDelete(noAvg,"Namespace " + ur.ns() + " does not exist.",dryRun); - ++delayedURDeletes; - ++deleted; - } else if (!Role.byName.containsKey(ur.role())) { - ur.delayDelete(noAvg,"Role " + ur.role() + " does not exist.",dryRun); - ++deleted; - ++delayedURDeletes; - } else if (ur.expires().before(tooLate)) { - if ("owner".equals(ur.rname())) { // don't delete Owners, even if Expired - urPrint.exec(noAvg,ur,"Owner Expired (but not deleted)"); - } else { - // In this case, when UR is expired, not dependent on other lookups, we delete straight out. - urDelete.exec(noAvg, ur,"Expired before " + tooLate); - ++deleted; - } - //trans.logAuditTrail(trans.info()); - } else if (ur.expires().before(future) && ur.expires().after(now)) { - ++count; - // Is there an Approval set already - boolean needNew = true; - if (ur.role()!=null && ur.user()!=null) { - List abm = Approval.byUser.get(ur.user()); - if (abm!=null) { - for (Approval a : abm) { - if (a.getOperation().equals(FUTURE_OP.A.name()) && ur.role().equals(a.getRole())) { - if (Future.data.get(a.getTicket())!=null) { - needNew = false; - break; - } - } - } - } - } - if (needNew) { - urFutureApprove.exec(noAvg, ur,""); - } - } - } - } - } catch (OrganizationException e) { - env.info().log(e,"Exiting ..."); - } finally { - env.info().log("Found",count,"user roles expiring before",future); - env.info().log("deleting",deleted,"user roles expiring before",tooLate); - } - - // Actualize UR Deletes, or send Email - if (UserRole.sizeForDeletion()>0) { - count+=UserRole.sizeForDeletion(); - double onePercent = 0.01; - if (((double)UserRole.sizeForDeletion())/UserRole.getData().size() > onePercent) { - Message msg = new Message(); - try { - msg.line("Found %d of %d UserRoles marked for Deletion in file %s", - delayedURDeletes,UserRole.getData().size(),deletesFile.getCanonicalPath()); - } catch (IOException e) { - msg.line("Found %d of %d UserRoles marked for Deletion.\n", - delayedURDeletes); - } - msg.line("Review the File. If data is ok, Use ExpiringP2 BatchProcess to complete the deletions"); - - email.msg(msg); - email.exec(trans, org, "Email Support"); - } else { - urDeleteF.flush(); - try { - BufferedReader br = new BufferedReader(new FileReader(deletesFile)); - try { - ExpiringP2.deleteURs(noAvg, br, urDelete, null /* don't touch Cache here*/); - } finally { - br.close(); - } - } catch (IOException io) { - noAvg.error().log(io); - } - } - } - if (count>0) { - String str = String.format("%d UserRoles modified or deleted", count); - cacheTouch.exec(trans, "user_role", str); - } - - // Run for Creds - trans.info().log("Checking for Expired Credentials"); - System.out.flush(); - count = 0; - try { - CredDAO.Data crd = new CredDAO.Data(); - Date last = null; - for ( Cred creds : Cred.data.values()) { - crd.id = creds.id; - for (int type : creds.types()) { - crd.type = type; - for ( Instance inst : creds.instances) { - if (inst.expires.before(tooLate)) { - crd.expires = inst.expires; - crDelete.exec(noAvg, crd,"Expired before " + tooLate); - } else if (last==null || inst.expires.after(last)) { - last = inst.expires; - } - } - if (last!=null) { - if (last.before(future)) { - crd.expires = last; - crPrint.exec(noAvg, crd,""); - ++count; - } - } - } - } - } finally { - String str = String.format("Found %d current creds expiring before %s", count, Chrono.dateOnlyStamp(future)); - if (count>0) { - cacheTouch.exec(trans, "cred", str); - } - } - - } - - @Override - protected void _close(AuthzTrans trans) { - trans.info().log("End",this.getClass().getSimpleName(),"processing" ); - for (Action action : new Action[] {crDelete}) { - if (action instanceof ActionDAO) { - ((ActionDAO)action).close(trans); - } - } - session.close(); - urDeleteF.close(); - urRecoverF.close(); - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java deleted file mode 100644 index dae62573..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java +++ /dev/null @@ -1,158 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.update; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.BatchPrincipal; -import org.onap.aaf.auth.actions.Action; -import org.onap.aaf.auth.actions.ActionDAO; -import org.onap.aaf.auth.actions.CacheTouch; -import org.onap.aaf.auth.actions.URDelete; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.cadi.util.Split; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.util.Chrono; - -public class ExpiringP2 extends Batch { - private final URDelete urDelete; - private final CacheTouch cacheTouch; - private final AuthzTrans noAvg; - private final BufferedReader urDeleteF; - - public ExpiringP2(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("batch:ExpiringP2")); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - urDelete = new URDelete(trans, cluster,isDryRun()); - TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = urDelete.getSession(trans); - } finally { - tt2.done(); - } - cacheTouch = new CacheTouch(trans,urDelete); - - File data_dir = new File(env.getProperty("aaf_data_dir")); - if (!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { - throw new IOException("Cannot read/write to Data Directory "+ data_dir.getCanonicalPath() + ": EXITING!!!"); - } - urDeleteF = new BufferedReader(new FileReader(new File(data_dir,"UserRoleDeletes.dat"))); - - } finally { - tt0.done(); - } - } - - @Override - protected void run(AuthzTrans trans) { - deleteURs(noAvg, urDeleteF, urDelete, cacheTouch); - } - - public static void deleteURs(AuthzTrans trans, BufferedReader urDeleteF, URDelete urDelete, CacheTouch cacheTouch) { - String line,prev=""; - try { - UserRole ur; - Map tally = new HashMap<>(); - int count=0; - try { - while ((line=urDeleteF.readLine())!=null) { - if (line.startsWith("#")) { - Count cnt = tally.get(line); - if (cnt==null) { - tally.put(line, cnt=new Count()); - } - cnt.inc(); - prev = line; - } else { - String[] l = Split.splitTrim('|', line); - try { - // Note: following default order from "COPY TO" - ur = new UserRole(l[0],l[1],l[3],l[4],Chrono.iso8601Fmt.parse(l[2])); - urDelete.exec(trans, ur, prev); - ++count; - } catch (ParseException e) { - trans.error().log(e); - } - } - } - - System.out.println("Tallies of UserRole Deletions"); - for (Entry es : tally.entrySet()) { - System.out.printf(" %6d\t%20s\n", es.getValue().cnt,es.getKey()); - } - } finally { - if (cacheTouch!=null && count>0) { - cacheTouch.exec(trans, "user_roles", "Removing UserRoles"); - } - } - } catch (IOException e) { - trans.error().log(e); - } - - } - private static class Count { - private int cnt=0; - - public /*synchonized*/ void inc() { - ++cnt; - } - - public String toString() { - return Integer.toString(cnt); - } - } - - @Override - protected void _close(AuthzTrans trans) { - trans.info().log("End",this.getClass().getSimpleName(),"processing" ); - for (Action action : new Action[] {urDelete,cacheTouch}) { - if (action instanceof ActionDAO) { - ((ActionDAO)action).close(trans); - } - } - session.close(); - try { - urDeleteF.close(); - } catch (IOException e) { - trans.error().log(e); - } - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java deleted file mode 100644 index 50c6dc21..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java +++ /dev/null @@ -1,236 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.update; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Map.Entry; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.BatchPrincipal; -import org.onap.aaf.auth.actions.Email; -import org.onap.aaf.auth.actions.EmailPrint; -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.dao.CassAccess; -import org.onap.aaf.auth.dao.cass.ApprovalDAO; -import org.onap.aaf.auth.dao.cass.FutureDAO; -import org.onap.aaf.auth.dao.cass.HistoryDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Approval; -import org.onap.aaf.auth.helpers.Future; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.auth.org.OrganizationFactory; -import org.onap.aaf.auth.org.Organization.Identity; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.util.Chrono; - -public class NotifyApprovals extends Batch { - private static final String LINE = "----------------------------------------------------------------"; - private final HistoryDAO historyDAO; - private final ApprovalDAO apprDAO; - private final FutureDAO futureDAO; - private Email email; - private int maxEmails; - private final PrintStream ps; - private final AuthzTrans noAvg; - - public NotifyApprovals(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("batch:NotifyApprovals")); - - historyDAO = new HistoryDAO(trans, cluster, CassAccess.KEYSPACE); - session = historyDAO.getSession(trans); - apprDAO = new ApprovalDAO(trans, historyDAO); - futureDAO = new FutureDAO(trans, historyDAO); - if (isDryRun()) { - email = new EmailPrint(); - maxEmails=3; - } else { - email = new Email(); - maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); - } - email.subject("AAF Approval Notification (ENV: %s)",batchEnv); - email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications." + - "\n Your approval is required, which you may enter on the following page:" - + "\n\n\t%s/approve\n\n" - ,env.getProperty(GUI_URL)); - email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n" - + "https://wiki.web.att.com/display/aaf/Contact+Us\n" - + "(Use 'Other Misc Requests (TOPS)')"); - - Approval.load(trans, session, Approval.v2_0_17); - Future.load(trans, session, Future.v2_0_17); // Skip the Construct Data - - ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true)); - ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":""); - } - - @Override - protected void run(AuthzTrans trans) { - GregorianCalendar gc = new GregorianCalendar(); - Date now = gc.getTime(); - String today = Chrono.dateOnlyStamp(now); - gc.add(GregorianCalendar.MONTH, -1); - gc=null; - - - Message msg = new Message(); - int emailCount = 0; - List pending = new ArrayList<>(); - boolean isOwner,isSupervisor; - for (Entry> es : Approval.byApprover.entrySet()) { - isOwner = isSupervisor = false; - String approver = es.getKey(); - if (approver.indexOf('@')<0) { - approver += org.getRealm(); - } - Date latestNotify=null, soonestExpire=null; - GregorianCalendar latest=new GregorianCalendar(); - GregorianCalendar soonest=new GregorianCalendar(); - pending.clear(); - - for (Approval app : es.getValue()) { - Future f = app.getTicket()==null?null:Future.data.get(app.getTicket()); - if (f==null) { // only Ticketed Approvals are valid.. the others are records. - // Approvals without Tickets are no longer valid. - if ("pending".equals(app.getStatus())) { - app.setStatus("lapsed"); - app.update(noAvg,apprDAO,dryRun); // obeys dryRun - } - } else { - if ((soonestExpire==null && f.expires()!=null) || (soonestExpire!=null && f.expires()!=null && soonestExpire.before(f.expires()))) { - soonestExpire=f.expires(); - } - - if ("pending".equals(app.getStatus())) { - if (!isOwner) { - isOwner = "owner".equals(app.getType()); - } - if (!isSupervisor) { - isSupervisor = "supervisor".equals(app.getType()); - } - - if ((latestNotify==null && app.getLast_notified()!=null) ||(latestNotify!=null && app.getLast_notified()!=null && latestNotify.before(app.getLast_notified()))) { - latestNotify=app.getLast_notified(); - } - pending.add(app); - } - } - } - - if (!pending.isEmpty()) { - boolean go = false; - if (latestNotify==null) { // never notified... make it so - go=true; - } else { - if (!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today - latest.setTime(latestNotify); - soonest.setTime(soonestExpire); - int year; - int days = soonest.get(GregorianCalendar.DAY_OF_YEAR)-latest.get(GregorianCalendar.DAY_OF_YEAR); - days+=((year=soonest.get(GregorianCalendar.YEAR))-latest.get(GregorianCalendar.YEAR))*365 + - (soonest.isLeapYear(year)?1:0); - if (days<7) { // If Expirations get within a Week (or expired), notify everytime. - go = true; - } - } - } - if (go) { - if (maxEmails>emailCount++) { - try { - Organization org = OrganizationFactory.obtain(env, approver); - Identity user = org.getIdentity(noAvg, approver); - if (user==null) { - ps.printf("Invalid Identity: %s\n", approver); - } else { - email.clear(); - msg.clear(); - email.addTo(user.email()); - msg.line(LINE); - msg.line("Why are you receiving this Notification?\n"); - if (isSupervisor) { - msg.line("%sYou are the supervisor of one or more employees who need access to tools which are protected by AAF. " + - "Your employees may ask for access to various tools and applications to do their jobs. ASPR requires " - + "that you are notified and approve their requests. The details of each need is provided when you click " - + "on webpage above.\n",isOwner?"1) ":""); - msg.line("Your participation in this process fulfills the ASPR requirement to re-authorize users in roles on a regular basis.\n\n"); - } - - if (isOwner) { - msg.line("%sYou are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " - + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. " - + "More info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n",isSupervisor?"2) ":""); - msg.line("Additionally, Credentials attached to the Namespace must be renewed regularly. While you may delegate certain functions to " + - "Administrators within your Namespace, you are ultimately responsible to make sure credentials do not expire.\n"); - msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n"); - msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); - - } - msg.line(" If you are unfamiliar with AAF, you might like to peruse the following links:" - + "\n\thttps://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell" - + "\n\thttps://wiki.web.att.com/display/aaf/The+New+Person%%27s+Guide+to+AAF"); - msg.line("\n SPECIAL NOTE about SWM Management Groups: Understand that SWM management Groups correlate one-to-one to AAF Namespaces. " - + "(SWM uses AAF for the Authorization piece of Management Groups). You may be assigned the SWM Management Group by asking " - + "directly, or through any of the above stated automated processes. Auto-generated Namespaces typically look like 'com.att.44444.PROD' " - + "where '44444' is a MOTS ID, and 'PROD' is PROD|DEV|TEST, etc. For your convenience, the MOTS link is http://ebiz.sbc.com/mots.\n"); - msg.line(" Finally, realize that there are automated processes which create Machines and Resources via SWM, Kubernetes or other " - + "such tooling. If you or your predecessor requested them, you were set as the owner of the AAF Namespace created during " - + "that process.\n"); - msg.line(" For ALL QUESTIONS of why and how of SWM, and whether you or your reports can be removed, please contact SWM at " - + "https://wiki.web.att.com/display/swm/Support\n"); - - email.msg(msg); - email.exec(noAvg, org,""); - if (!isDryRun()) { - email.log(ps,"NotifyApprovals"); - for (Approval app : pending) { - app.setLastNotified(now); - app.update(noAvg, apprDAO, dryRun); - } - } - } - } catch (OrganizationException e) { - trans.info().log(e); - } - } - } - } - } - trans.info().printf("%d emails sent for %s", emailCount,batchEnv); - } - - @Override - protected void _close(AuthzTrans trans) { - futureDAO.close(trans); - apprDAO.close(trans); - historyDAO.close(trans); - ps.close(); - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java deleted file mode 100644 index 848b54e8..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java +++ /dev/null @@ -1,394 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.update; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.BatchPrincipal; -import org.onap.aaf.auth.actions.Email; -import org.onap.aaf.auth.actions.EmailPrint; -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.dao.hl.Question; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Cred; -import org.onap.aaf.auth.helpers.NS; -import org.onap.aaf.auth.helpers.Notification; -import org.onap.aaf.auth.helpers.Notification.TYPE; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.auth.org.EmailWarnings; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.Organization.Identity; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.auth.org.OrganizationFactory; -import org.onap.aaf.cadi.CadiException; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.util.Chrono; - - -public class NotifyCredExpiring extends Batch { - - private static final String UNKNOWN_ID = "unknown@deprecated.id"; - private static final String AAF_INSTANTIATED_MECHID = "AAF INSTANTIATED MECHID"; - private static final String EXPIRATION_DATE = "EXPIRATION DATE"; - private static final String QUICK_LINK = "QUICK LINK TO UPDATE PAGE"; - private static final String DASH_1 = "-----------------------"; - private static final String DASH_2 = "---------------"; - private static final String DASH_3 = "----------------------------------------------------"; - private static final String LINE = "\n----------------------------------------------------------------"; - private Email email; - private int maxEmails; - private final PrintStream ps; - private final AuthzTrans noAvg; - private String supportEmailAddr; - private CSV csv; - private CSVInfo csvInfo; - - public NotifyCredExpiring(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring")); - - if (isDryRun()) { - email = new EmailPrint(); - maxEmails=3; - maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); - } else { - email = new Email(); - maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); - } - - email.subject("AAF Password Expiration Notification (ENV: %s)",batchEnv); - email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications.\n\n" + - " The following Credentials are expiring on the dates shown. Failure to act before the expiration date " - + "will cause your App's Authentications to fail.\n"); - email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n" - + "https://wiki.web.att.com/display/aaf/Contact+Us\n" - + "(Use 'Other Misc Requests (TOPS)')"); - - boolean quit = false; - if(args().length<1) { - System.err.println("Need CSV formatted Expiring Report"); - quit = true; - } else { - File f = new File(logDir(),args()[0]); - System.out.println("Reading " + f.getCanonicalPath()); - csv = new CSV(f); - } - - if(args().length<2) { - System.err.println("Need Email Template"); - //quit = true; - } - if(quit) { - System.exit(2); - } - - csvInfo = new CSVInfo(System.err); - try { - csv.visit(csvInfo); - } catch (CadiException e) { - throw new APIException(e); - } - - Notification.load(trans, session, Notification.v2_0_18); - - ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true)); - ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":""); - } - - @Override - protected void run(AuthzTrans trans) { - - // Temp structures - Map> ownerCreds = new TreeMap<>(); - - - List noOwner = new ArrayList<>(); - ownerCreds.put(UNKNOWN_ID,noOwner); - int emailCount=0; - -// // Get a list of ONLY the ones needing email by Owner -// for (Entry> es : Cred.byNS.entrySet()) { -// for (Cred c : es.getValue()) { -// List ownerURList = UserRole.getByRole().get(es.getKey()+".owner"); -// if (ownerURList!=null) { -// for (UserRole ur:ownerURList) { -// String owner = ur.user(); -// List llc = ownerCreds.get(owner); -// if (llc==null) { -// ownerCreds.put(owner, (llc=new ArrayList<>())); -// } -// llc.add(new LastCred(c,last)); -// } -// } else { -// noOwner.add(new LastCred(c,last)); -// } -// } -// } -// -// boolean bCritical,bNormal,bEarly; -// Message msg = new Message(); -// Notification ownNotf; -// StringBuilder logMessage = new StringBuilder(); -// for (Entry> es : ownerCreds.entrySet()) { -// String owner = es.getKey(); -// boolean header = true; -// try { -// Organization org = OrganizationFactory.obtain(env, owner); -// Identity user = org.getIdentity(noAvg, owner); -// if (!UNKNOWN_ID.equals(owner) && user==null) { -// ps.printf("Invalid Identity: %s\n", owner); -// } else { -// logMessage.setLength(0); -// if (maxEmails>emailCount) { -// bCritical=bNormal=bEarly = false; -// email.clear(); -// msg.clear(); -// email.addTo(user==null?supportEmailAddr:user.email()); -// -// ownNotf = Notification.get(es.getKey(),TYPE.CN); -// if (ownNotf==null) { -// ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN); -// } -// last = ownNotf.last; -// // Get Max ID size for formatting purposes -// int length = AAF_INSTANTIATED_MECHID.length(); -// for (LastCred lc : es.getValue()) { -// length = Math.max(length, lc.cred.id.length()); -// } -// String id_exp_fmt = "\t%-"+length+"s %15s %s"; -// -// Collections.sort(es.getValue(),LastCred.COMPARE); -// for (LastCred lc : es.getValue()) { -// if (lc.last.after(must) && lc.last.before(early) && -// (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { -// if (!bEarly && header) { -// msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early. " -// + "You will be reminded next month\n"); -// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); -// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); -// header = false; -// } -// bEarly = true; -// } else if (lc.last.after(critical) && lc.last.before(must) && -// (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { -// if (!bNormal) { -// boolean last2wks = lc.last.before(within2Weeks); -// if (last2wks) { -// try { -// Identity supvsr = user.responsibleTo(); -// email.addCC(supvsr.email()); -// } catch (OrganizationException e) { -// trans.error().log(e, "Supervisor cannot be looked up"); -// } -// } -// if (header) { -// msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" + -// (last2wks?"\tNote: Your Supervisor is CCd\n":"\tNote: Your Supervisor will be notified if this is not being done before the last 2 weeks\n")); -// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); -// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); -// } -// header = false; -// } -// bNormal=true; -// } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor -// if (!bCritical && header) { -// msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" + -// "\tYour supervisor is added to this Email\n"); -// msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); -// msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3); -// header = false; -// } -// bCritical = true; -// try { -// if (user!=null) { -// Identity supvsr = user.responsibleTo(); -// if (supvsr!=null) { -// email.addCC(supvsr.email()); -// supvsr = supvsr.responsibleTo(); -// if (supvsr!=null) { -// email.addCC(supvsr.email()); -// } -// } -// } -// } catch (OrganizationException e) { -// trans.error().log(e, "Supervisor cannot be looked up"); -// } -// } -// if (bEarly || bNormal || bCritical) { -// if (logMessage.length()==0) { -// logMessage.append("NotifyCredExpiring"); -// } -// logMessage.append("\n\t"); -// logMessage.append(lc.cred.id); -// logMessage.append('\t'); -// logMessage.append(Chrono.dateOnlyStamp(lc.last)); -// msg.line(id_exp_fmt, lc.cred.id, Chrono.dateOnlyStamp(lc.last)+" ",env.getProperty(GUI_URL)+"/creddetail?ns="+Question.domain2ns(lc.cred.id)); -// } -// } -// -// if (bEarly || bNormal || bCritical) { -// msg.line(LINE); -// msg.line("Why are you receiving this Notification?\n"); -// msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " -// + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. " -// + "You might like https://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell. More detailed info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n"); -// msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n"); -// msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); -// email.msg(msg); -// Result rv = email.exec(trans, org,""); -// if (rv.isOK()) { -// ++emailCount; -// if (!isDryRun()) { -// ownNotf.update(noAvg, session, false); -// // SET LastNotification -// } -// email.log(ps,logMessage.toString()); -// } else { -// trans.error().log(rv.errorString()); -// } -// } -// } -// } -// } catch (OrganizationException e) { -// trans.info().log(e); -// } -// } - trans.info().printf("%d emails sent for %s", emailCount,batchEnv); - } - - - private static class CSVInfo implements CSV.Visitor { - private PrintStream out; - private Set unsupported; - private NotifyCredVisitor credv; - private List llc; - - public CSVInfo(PrintStream out) { - this.out = out; - credv = new NotifyCredVisitor(llc = new ArrayList<>()); - } - - @Override - public void visit(List row) throws IOException, CadiException { - - switch(row.get(0)) { - case NotifyCredVisitor.SUPPORTS: - credv.visit(row); - break; - default: - if(unsupported==null) { - unsupported = new HashSet(); - } - if(!unsupported.contains(row.get(0))) { - unsupported.add(row.get(0)); - out.println("Unsupported Type: " + row.get(0)); - } - } - } - } - - private static class Contact { - public List contacts; - private List owners; - - public Contact(final String ns) { - contacts = new ArrayList<>(); - loadFromNS(ns); - } - - public void loadFromNS(final String ns) { - owners = UserRole.getByRole().get(ns+".owner"); - } - } - - private static class LastCred extends Contact { - public final String id; - public final int type; - public final Date expires; - - public LastCred(final String id, final String ns, final int type, final Date expires) { - super(ns); - this.id = id; - this.type = type; - this.expires = expires; - } - } - - private static class NotifyCredVisitor implements CSV.Visitor { - public static final String SUPPORTS = "cred"; - private final List lastCred; - - public NotifyCredVisitor(final List lastCred) { - this.lastCred = lastCred; - } - - @Override - public void visit(List row) throws IOException, CadiException { - try { - lastCred.add(new LastCred( - row.get(1), - row.get(2), - Integer.parseInt(row.get(3)), - Chrono.dateOnlyFmt.parse(row.get(4)) - ) - ); - } catch (NumberFormatException | ParseException e) { - throw new CadiException(e); - } - } - } - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - ps.close(); - } -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Remove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Remove.java deleted file mode 100644 index d35cfd34..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Remove.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.update; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.BatchPrincipal; -import org.onap.aaf.auth.actions.CacheTouch; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.CQLBatch; -import org.onap.aaf.auth.helpers.Cred; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.helpers.X509; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.cadi.CadiException; -import org.onap.aaf.cadi.client.Holder; -import org.onap.aaf.cadi.util.CSV; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.util.Chrono; - -public class Remove extends Batch { - private final AuthzTrans noAvg; - private CacheTouch cacheTouch; - private CQLBatch cqlBatch; - - public Remove(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("batch:RemoveExpired")); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - cacheTouch = new CacheTouch(trans, cluster, dryRun); - TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cacheTouch.getSession(trans); - } finally { - tt2.done(); - } - cqlBatch = new CQLBatch(session); - - - } finally { - tt0.done(); - } - } - - @Override - protected void run(AuthzTrans trans) { - final int maxBatch = 50; - - // Create Intermediate Output - File logDir = new File(logDir()); - - File expired = new File(logDir,"Delete"+Chrono.dateOnlyStamp()+".csv"); - CSV expiredCSV = new CSV(expired); - try { - final StringBuilder sb = cqlBatch.begin(); - final Holder hi = new Holder(0); - expiredCSV.visit(new CSV.Visitor() { - @Override - public void visit(List row) throws IOException, CadiException { - int i = hi.get(); - if(i>=maxBatch) { - cqlBatch.execute(dryRun); - hi.set(0); - cqlBatch.begin(); - i=0; - } - switch(row.get(0)) { - case "ur": - hi.set(++i); - UserRole.row(sb,row); - break; - case "cred": - hi.set(++i); - Cred.row(sb,row); - break; - case "x509": - hi.set(++i); - X509.row(sb,row); - break; - } - } - }); - cqlBatch.execute(dryRun); - } catch (IOException | CadiException e) { - e.printStackTrace(); - } - } - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - cacheTouch.close(trans); - } - -} diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Upload.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Upload.java deleted file mode 100644 index a670f37d..00000000 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Upload.java +++ /dev/null @@ -1,313 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - */ - -package org.onap.aaf.auth.update; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.misc.env.APIException; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.TimeTaken; - -import com.datastax.driver.core.ResultSet; - -public class Upload extends Batch { - public Upload(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - - } finally { - tt0.done(); - } - } - - private static final int BATCH_LENGTH = 100; - - int count,batchCnt; - - @Override - protected void run(AuthzTrans trans) { - String line; - StringBuilder sb = new StringBuilder(); - StringBuilder query = new StringBuilder(); - List array = new ArrayList(); - for(String feed : args()) { - File file = new File(feed + ".dat"); - TimeTaken tt = trans.start(file.getAbsolutePath(), Env.SUB); - System.out.println("#### Running " + feed + ".dat Feed ####"); - try { - - if(file.exists()) { - count=batchCnt=0; - boolean justOne = false; - try { - BufferedReader br = new BufferedReader(new FileReader(file)); - try { - while((line=br.readLine())!=null) { - if(line.length()>5000) { - if(query.length()>0) { - applyBatch(query); - justOne=true; - } - } - if(query.length()==0) { - query.append("BEGIN BATCH\n"); - } - // Split into fields, first turning Escaped values into something we can convert back from - char c=0; - boolean inQuote = false; - int fldcnt = 0; - - for(int i=0;i0) { - applyBatch(query); - } - - } finally { - br.close(); - sb.setLength(0); - query.setLength(0); - } - - } catch (IOException e) { - trans.error().log(e); - e.printStackTrace(); - } - - } else { - trans.error().log("No file found: ", file.getAbsolutePath()); - } - } finally { - tt.done(); - System.err.flush(); - System.out.printf("\n%d applied in %d batches\n",count,batchCnt); - } - - } - - } - - // APPROVALS - private static final String APPR_INS_FMT=" INSERT INTO authz.approval " - + "(id,approver,last_notified,memo,operation,status,ticket,type,user) " - + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);\n"; - private static final Boolean[] APPR_QUOTES = new Boolean[]{false,true,true,true,true,true,false,true,true}; - - // ARTIFACTS - private static final String ARTI_INS_FMT=" INSERT INTO authz.artifact " - + "(mechid,machine,ca,dir,expires,notify,ns,os_user,renewdays,sans,sponsor,type) " - + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);\n"; - private static final Boolean[] ARTI_QUOTES = new Boolean[] - {true,true,true,true,true,true,true,true,false,false,true,false}; - - // CREDS - private static final String CRED_INS_FMT=" INSERT INTO authz.cred " - + "(id,type,expires,cred,notes,ns,other,prev) " - + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s);\n"; - private static final Boolean[] CRED_QUOTES = new Boolean[] - {true,false,true,false,true,true,false,false}; - - // NS - private static final String NS_INS_FMT=" INSERT INTO authz.ns " - + "(name,description,parent,scope,type) " - + "VALUES (%s,%s,%s,%s,%s);\n"; - private static final Boolean[] NS_QUOTES = new Boolean[] - {true,true,true,false,false}; - - // x509 - private static final String X509_INS_FMT=" INSERT INTO authz.x509 " - + "(ca,serial,id,x500,x509) " - + "VALUES (%s,%s,%s,%s,%s);\n"; - private static final Boolean[] X509_QUOTES = new Boolean[] - {true,false,true,true,true}; - - // ROLE - private static final String ROLE_INS_FMT=" INSERT INTO authz.role " - + "(ns,name,description,perms) " - + "VALUES (%s,%s,%s,%s);\n"; - private static final Boolean[] ROLE_QUOTES = new Boolean[] - {true,true,true,false}; - // ROLE - private static final String PERM_INS_FMT=" INSERT INTO authz.perm " - + "(ns,type,instance,action,description,roles) " - + "VALUES (%s,%s,%s,%s,%s,%s);\n"; - private static final Boolean[] PERM_QUOTES = new Boolean[] - {true,true,true,true,true,false}; - - - private String build(String feed, List array) { - String rv; - switch(feed) { - case "approval": - rv = String.format(APPR_INS_FMT,array.toArray()); - break; - case "artifact": - rv = String.format(ARTI_INS_FMT,array.toArray()); - break; - case "cred": - rv = String.format(CRED_INS_FMT,array.toArray()); - break; - case "ns": - rv = String.format(NS_INS_FMT,array.toArray()); - break; - case "role": - rv = String.format(ROLE_INS_FMT,array.toArray()); - break; - case "perm": - rv = String.format(PERM_INS_FMT,array.toArray()); - break; - case "x509": - rv = String.format(X509_INS_FMT,array.toArray()); - break; - default: - rv = ""; - } - array.clear(); - return rv; - } - - private void addField(String feed, int fldcnt, List array, StringBuilder sb) { - Boolean[] ba; - switch(feed) { - case "approval": - ba = APPR_QUOTES; - break; - case "artifact": - ba = ARTI_QUOTES; - break; - case "cred": - ba = CRED_QUOTES; - break; - case "ns": - ba = NS_QUOTES; - break; - case "role": - ba = ROLE_QUOTES; - break; - case "perm": - ba = PERM_QUOTES; - break; - case "x509": - ba = X509_QUOTES; - break; - default: - ba = null; - } - if(ba!=null) { - if(sb.toString().length()==0) { - array.add("null"); - } else { - if(ba[fldcnt]) { - String s = null; - if(sb.indexOf("'")>=0) { - s = sb.toString().replace("'","''"); - } - if(sb.indexOf("\\n")>=0) { - if(s==null) { - s = sb.toString().replace("\\n","\n"); - } else { - s = s.replace("\\n","\n"); - } - } - if(sb.indexOf("\\t")>=0) { - if(s==null) { - s = sb.toString().replace("\\t","\t"); - } else { - s = s.replace("\\t","\t"); - } - } - if(s==null) { - array.add("'" + sb + '\''); - } else { - array.add("'" + s + '\''); - } - } else { - array.add(sb.toString()); - } - } - sb.setLength(0); - } - } - - private void applyBatch(StringBuilder query) { - try { - query.append("APPLY BATCH;"); - ResultSet rv = session.execute(query.toString()); - if(rv.wasApplied()) { - System.out.print('.'); - if((++batchCnt % 60)==0) { - System.out.println(); - } - } else { - System.out.print("Data NOT APPLIED"); - } - } finally { - query.setLength(0); - } - } - - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - } - -} - diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_ActionDAO.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_ActionDAO.java deleted file mode 100644 index 254a6adf..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_ActionDAO.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.actions.ActionDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.APIException; - -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.Configuration; -import com.datastax.driver.core.Cluster.Initializer; -import com.datastax.driver.core.Host.StateListener; - -import static org.mockito.Mockito.*; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.List; - -import org.junit.Test; - -public class JU_ActionDAO { - - AuthzTrans aTrans; - Cluster cluster; - ActionDAOStub actionDAOStub; - ActionDAOStub actionDAOStub1; - - private class ActionDAOStub extends ActionDAO { - - public ActionDAOStub(AuthzTrans trans, ActionDAO predecessor) { - super(trans, predecessor); - // TODO Auto-generated constructor stub - } - - public ActionDAOStub(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { - super(trans, cluster, dryRun); - // TODO Auto-generated constructor stub - } - - @Override - public Result exec(AuthzTrans trans, Object data, Object t) { - // TODO Auto-generated method stub - return null; - } - - } - - @Before - public void setUp() throws APIException, IOException { -// Cluster.Initializer cInit = mock(Cluster.Initializer.class); -// Cluster.Builder cBuild = new Cluster.Builder(); -// cBuild.addContactPoint("test"); -// cBuild.build(); -// cluster.buildFrom(cBuild); -// cluster.builder(); -// cluster.init(); -// cluster.builder().getContactPoints(); - - - -// aTrans = mock(AuthzTrans.class); -// cluster = mock(Cluster.class); -// actionDAOStub = new ActionDAOStub(aTrans,cluster,true); -// actionDAOStub1 = new ActionDAOStub(aTrans, actionDAOStub); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_CredPrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_CredPrintTest.java deleted file mode 100644 index 2e6ad09c..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_CredPrintTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.aaf.auth.actions.CredPrint; -import org.onap.aaf.auth.dao.cass.CredDAO; -import org.onap.aaf.auth.dao.cass.CredDAO.Data; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.LogTarget; - -public class JU_CredPrintTest { - - @Mock - private AuthzTrans trans; - private Data cred; - @Mock - LogTarget target; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(trans.info()).thenReturn(target); - cred = new CredDAO.Data(); - cred.type = CredDAO.BASIC_AUTH; - } - - @Test - public void testCred() { - CredPrint print = new CredPrint("text"); - - Result result = print.exec(trans, cred, "text"); - - assertEquals(result.status, result.ok().status); - assertEquals(CredPrint.type(CredDAO.BASIC_AUTH), "OLD"); - assertEquals(CredPrint.type(CredDAO.BASIC_AUTH_SHA256), "U/P"); - assertEquals(CredPrint.type(CredDAO.CERT_SHA256_RSA), "Cert"); - assertEquals(CredPrint.type(0), "Unknown"); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Email.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Email.java deleted file mode 100644 index d3d4719e..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Email.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.actions.Email; -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.Organization.Identity; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.OrganizationException; - -import static org.mockito.Mockito.*; - -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.Collection; -import java.util.Hashtable; -import java.util.Set; - -import org.junit.Test; - -public class JU_Email { - - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - Email email; - Identity usersI; - Message msg; - PrintStream ps; - - @Before - public void setUp() throws FileNotFoundException { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - ps = new PrintStream(errStream); - System.setOut(new PrintStream(outStream)); - System.setErr(ps); - - usersI = mock(Identity.class); - msg = new Message(); - email = new Email(); - } - - @Test - public void testClear() { - Assert.assertNotNull(email.clear()); - } - - @Test - public void testIndent() { - email.indent("indent"); - } - - @Test - public void testPreamble() { - email.preamble("format"); - } - - @Test - public void testAddTo() { - email.addTo(usersI); - -// Collection col = mock(Collection.class); -// col.add("test"); -// email.addTo(col); - - email.addTo("email"); - } - - @Test - public void testAddCC() { - email.addCC(usersI); - email.addCC("email"); - } - -// @Test -// public void testAdd() throws OrganizationException { -// email.add(usersI, true); -// } - - @Test - public void testSubject() { - email.subject("format"); - email.subject("for%smat","format"); - } - - @Test - public void testSignature() { - email.signature("format","arg"); - } - - @Test - public void testMsg() { - email.msg(msg); - } - - @Test - public void testExec() { - AuthzTrans trans = mock(AuthzTrans.class); - Organization org = mock(Organization.class); - email.preamble("format"); - email.msg(msg); - email.signature("format","arg"); - - email.exec(trans, org, "text"); - } - - @Test - public void testLog() throws FileNotFoundException { - email.addTo("email"); - email.addCC("email"); - email.log(ps, "email"); - email.addTo("emails"); - email.addCC("emails"); - email.log(ps, "emails"); - } - - @After - public void cleanUp() { - System.setErr(System.err); - System.setOut(System.out); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_EmailPrint.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_EmailPrint.java deleted file mode 100644 index fe87219b..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_EmailPrint.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.actions.EmailPrint; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.cadi.client.Future; -import org.onap.aaf.cadi.client.Rcli; - -import static org.mockito.Mockito.*; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.Test; - -public class JU_EmailPrint { - - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - EmailPrint ePrint; - AuthzTrans trans; - Organization org; - StringBuilder strBuilder; - - @Before - public void setUp() { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - ePrint = new EmailPrint(); - trans = mock(AuthzTrans.class); - org = mock(Organization.class); - strBuilder = new StringBuilder(); - strBuilder.append("test\nte\nst"); - ePrint.addTo("test"); - ePrint.addTo("test1"); - ePrint.addTo("test2"); - ePrint.addCC("test"); - ePrint.addCC("test1"); - ePrint.addCC("test2"); - - } - - @Test - public void testExec() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class c = ePrint.getClass(); - Class[] cArg = new Class[3]; - cArg[0] = AuthzTrans.class; - cArg[1] = Organization.class; - cArg[2] = StringBuilder.class;//Steps to test a protected method - Method execMethod = c.getDeclaredMethod("exec", cArg); - execMethod.setAccessible(true); - execMethod.invoke(ePrint, trans, org, strBuilder); - } - - @After - public void cleanUp() { - System.setErr(System.err); - System.setOut(System.out); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_FuturePrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_FuturePrintTest.java deleted file mode 100644 index 121bf48f..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_FuturePrintTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.util.Calendar; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.aaf.auth.actions.FuturePrint; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Future; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.LogTarget; - -public class JU_FuturePrintTest { - @Mock - private AuthzTrans trans; - @Mock - LogTarget target; - private Future future; - - @Before - public void setUp() throws Exception { - initMocks(this); - future = new Future(new UUID(1l, 1l), "memo", "target", Calendar.getInstance().getTime(), - Calendar.getInstance().getTime(), null); - when(trans.info()).thenReturn(target); - } - - @Test - public void testURFuturePrint() { - FuturePrint print = new FuturePrint("Info Text"); - assertEquals(Result.ok().status, print.exec(trans, future, "text").status); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Message.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Message.java deleted file mode 100644 index ada1dbae..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_Message.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.actions.Message; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_Message { - - Message msg; - - @Before - public void setUp() { - msg = new Message(); - } - - @Test - public void testLine() { - msg.line("test"); - } - - @Test - public void testClear() { - msg.clear(); - } - - @Test - public void testMsg() { - StringBuilder sb = new StringBuilder(); - msg.line("test"); - msg.line("test1"); - msg.msg(sb, "indent"); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URFuturePrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URFuturePrintTest.java deleted file mode 100644 index 95406425..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URFuturePrintTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.util.Calendar; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.aaf.auth.actions.URFuturePrint; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.LogTarget; - -public class JU_URFuturePrintTest { - @Mock - private AuthzTrans trans; - @Mock - LogTarget target; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(trans.info()).thenReturn(target); - } - - @Test - public void testURFuturePrint() { - URFuturePrint print = new URFuturePrint("Info Text"); - UserRole ur = new UserRole("user", "ns", "rname", Calendar.getInstance().getTime()); - assertEquals(Result.ok().status, print.exec(trans, ur, "text").status); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URPrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URPrintTest.java deleted file mode 100644 index 1e99ec66..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/actions/test/JU_URPrintTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.actions.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.util.Calendar; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.aaf.auth.actions.URPrint; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.LogTarget; - -public class JU_URPrintTest { - @Mock - private AuthzTrans trans; - @Mock - LogTarget target; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(trans.info()).thenReturn(target); - } - - @Test - public void testURPrint() { - URPrint print = new URPrint("Info Text"); - UserRole ur = new UserRole("user", "ns", "rname", Calendar.getInstance().getTime()); - assertEquals(Result.ok().status, print.exec(trans, ur, "text").status); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_ActionDAO.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_ActionDAO.java new file mode 100644 index 00000000..9376da4b --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_ActionDAO.java @@ -0,0 +1,95 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.actions.ActionDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.APIException; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Configuration; +import com.datastax.driver.core.Cluster.Initializer; +import com.datastax.driver.core.Host.StateListener; + +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.List; + +import org.junit.Test; + +public class JU_ActionDAO { + + AuthzTrans aTrans; + Cluster cluster; + ActionDAOStub actionDAOStub; + ActionDAOStub actionDAOStub1; + + private class ActionDAOStub extends ActionDAO { + + public ActionDAOStub(AuthzTrans trans, ActionDAO predecessor) { + super(trans, predecessor); + // TODO Auto-generated constructor stub + } + + public ActionDAOStub(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException { + super(trans, cluster, dryRun); + // TODO Auto-generated constructor stub + } + + @Override + public Result exec(AuthzTrans trans, Object data, Object t) { + // TODO Auto-generated method stub + return null; + } + + } + + @Before + public void setUp() throws APIException, IOException { +// Cluster.Initializer cInit = mock(Cluster.Initializer.class); +// Cluster.Builder cBuild = new Cluster.Builder(); +// cBuild.addContactPoint("test"); +// cBuild.build(); +// cluster.buildFrom(cBuild); +// cluster.builder(); +// cluster.init(); +// cluster.builder().getContactPoints(); + + + +// aTrans = mock(AuthzTrans.class); +// cluster = mock(Cluster.class); +// actionDAOStub = new ActionDAOStub(aTrans,cluster,true); +// actionDAOStub1 = new ActionDAOStub(aTrans, actionDAOStub); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_CredPrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_CredPrintTest.java new file mode 100644 index 00000000..ebb307c2 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_CredPrintTest.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aaf.auth.batch.actions.CredPrint; +import org.onap.aaf.auth.dao.cass.CredDAO; +import org.onap.aaf.auth.dao.cass.CredDAO.Data; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.LogTarget; + +public class JU_CredPrintTest { + + @Mock + private AuthzTrans trans; + private Data cred; + @Mock + LogTarget target; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(trans.info()).thenReturn(target); + cred = new CredDAO.Data(); + cred.type = CredDAO.BASIC_AUTH; + } + + @Test + public void testCred() { + CredPrint print = new CredPrint("text"); + + Result result = print.exec(trans, cred, "text"); + + assertEquals(result.status, result.ok().status); + assertEquals(CredPrint.type(CredDAO.BASIC_AUTH), "OLD"); + assertEquals(CredPrint.type(CredDAO.BASIC_AUTH_SHA256), "U/P"); + assertEquals(CredPrint.type(CredDAO.CERT_SHA256_RSA), "Cert"); + assertEquals(CredPrint.type(0), "Unknown"); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Email.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Email.java new file mode 100644 index 00000000..3a170679 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Email.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.actions.Email; +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.Organization.Identity; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.OrganizationException; + +import static org.mockito.Mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.PrintStream; +import java.util.Collection; +import java.util.Hashtable; +import java.util.Set; + +import org.junit.Test; + +public class JU_Email { + + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + Email email; + Identity usersI; + Message msg; + PrintStream ps; + + @Before + public void setUp() throws FileNotFoundException { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + ps = new PrintStream(errStream); + System.setOut(new PrintStream(outStream)); + System.setErr(ps); + + usersI = mock(Identity.class); + msg = new Message(); + email = new Email(); + } + + @Test + public void testClear() { + Assert.assertNotNull(email.clear()); + } + + @Test + public void testIndent() { + email.indent("indent"); + } + + @Test + public void testPreamble() { + email.preamble("format"); + } + + @Test + public void testAddTo() { + email.addTo(usersI); + +// Collection col = mock(Collection.class); +// col.add("test"); +// email.addTo(col); + + email.addTo("email"); + } + + @Test + public void testAddCC() { + email.addCC(usersI); + email.addCC("email"); + } + +// @Test +// public void testAdd() throws OrganizationException { +// email.add(usersI, true); +// } + + @Test + public void testSubject() { + email.subject("format"); + email.subject("for%smat","format"); + } + + @Test + public void testSignature() { + email.signature("format","arg"); + } + + @Test + public void testMsg() { + email.msg(msg); + } + + @Test + public void testExec() { + AuthzTrans trans = mock(AuthzTrans.class); + Organization org = mock(Organization.class); + email.preamble("format"); + email.msg(msg); + email.signature("format","arg"); + + email.exec(trans, org, "text"); + } + + @Test + public void testLog() throws FileNotFoundException { + email.addTo("email"); + email.addCC("email"); + email.log(ps, "email"); + email.addTo("emails"); + email.addCC("emails"); + email.log(ps, "emails"); + } + + @After + public void cleanUp() { + System.setErr(System.err); + System.setOut(System.out); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_EmailPrint.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_EmailPrint.java new file mode 100644 index 00000000..64d02ee3 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_EmailPrint.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.actions.EmailPrint; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.cadi.client.Future; +import org.onap.aaf.cadi.client.Rcli; + +import static org.mockito.Mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.Test; + +public class JU_EmailPrint { + + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + EmailPrint ePrint; + AuthzTrans trans; + Organization org; + StringBuilder strBuilder; + + @Before + public void setUp() { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + ePrint = new EmailPrint(); + trans = mock(AuthzTrans.class); + org = mock(Organization.class); + strBuilder = new StringBuilder(); + strBuilder.append("test\nte\nst"); + ePrint.addTo("test"); + ePrint.addTo("test1"); + ePrint.addTo("test2"); + ePrint.addCC("test"); + ePrint.addCC("test1"); + ePrint.addCC("test2"); + + } + + @Test + public void testExec() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class c = ePrint.getClass(); + Class[] cArg = new Class[3]; + cArg[0] = AuthzTrans.class; + cArg[1] = Organization.class; + cArg[2] = StringBuilder.class;//Steps to test a protected method + Method execMethod = c.getDeclaredMethod("exec", cArg); + execMethod.setAccessible(true); + execMethod.invoke(ePrint, trans, org, strBuilder); + } + + @After + public void cleanUp() { + System.setErr(System.err); + System.setOut(System.out); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_FuturePrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_FuturePrintTest.java new file mode 100644 index 00000000..00542a2f --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_FuturePrintTest.java @@ -0,0 +1,61 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.Calendar; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aaf.auth.batch.actions.FuturePrint; +import org.onap.aaf.auth.batch.helpers.Future; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.LogTarget; + +public class JU_FuturePrintTest { + @Mock + private AuthzTrans trans; + @Mock + LogTarget target; + private Future future; + + @Before + public void setUp() throws Exception { + initMocks(this); + future = new Future(new UUID(1l, 1l), "memo", "target", Calendar.getInstance().getTime(), + Calendar.getInstance().getTime(), null); + when(trans.info()).thenReturn(target); + } + + @Test + public void testURFuturePrint() { + FuturePrint print = new FuturePrint("Info Text"); + assertEquals(Result.ok().status, print.exec(trans, future, "text").status); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Message.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Message.java new file mode 100644 index 00000000..86bab83e --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_Message.java @@ -0,0 +1,62 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.actions.Message; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_Message { + + Message msg; + + @Before + public void setUp() { + msg = new Message(); + } + + @Test + public void testLine() { + msg.line("test"); + } + + @Test + public void testClear() { + msg.clear(); + } + + @Test + public void testMsg() { + StringBuilder sb = new StringBuilder(); + msg.line("test"); + msg.line("test1"); + msg.msg(sb, "indent"); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URFuturePrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URFuturePrintTest.java new file mode 100644 index 00000000..9f569d65 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URFuturePrintTest.java @@ -0,0 +1,57 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.Calendar; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aaf.auth.batch.actions.URFuturePrint; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.LogTarget; + +public class JU_URFuturePrintTest { + @Mock + private AuthzTrans trans; + @Mock + LogTarget target; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(trans.info()).thenReturn(target); + } + + @Test + public void testURFuturePrint() { + URFuturePrint print = new URFuturePrint("Info Text"); + UserRole ur = new UserRole("user", "ns", "rname", Calendar.getInstance().getTime()); + assertEquals(Result.ok().status, print.exec(trans, ur, "text").status); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URPrintTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URPrintTest.java new file mode 100644 index 00000000..8a037ece --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/actions/test/JU_URPrintTest.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.actions.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.Calendar; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aaf.auth.batch.actions.URPrint; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.LogTarget; + +public class JU_URPrintTest { + @Mock + private AuthzTrans trans; + @Mock + LogTarget target; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(trans.info()).thenReturn(target); + } + + @Test + public void testURPrint() { + URPrint print = new URPrint("Info Text"); + UserRole ur = new UserRole("user", "ns", "rname", Calendar.getInstance().getTime()); + assertEquals(Result.ok().status, print.exec(trans, ur, "text").status); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java new file mode 100644 index 00000000..661105d3 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java @@ -0,0 +1,434 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ +package org.onap.aaf.auth.batch.helpers.creators; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.LocalDate; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Token; +import com.datastax.driver.core.TupleValue; +import com.datastax.driver.core.TypeCodec; +import com.datastax.driver.core.UDTValue; +import com.google.common.reflect.TypeToken; + +public class RowCreator { + + public static Row getRow() { + Row row = new Row() { + + @Override + public boolean isNull(String name) { + // TODO Auto-generated method stub + return false; + } + + @Override + public BigInteger getVarint(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UUID getUUID(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UDTValue getUDTValue(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public TupleValue getTupleValue(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getTimestamp(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getTime(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getString(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public short getShort(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public Set getSet(String name, TypeToken elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getSet(String name, Class elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getObject(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getMap(String name, TypeToken keysType, TypeToken valuesType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getMap(String name, Class keysClass, Class valuesClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getLong(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public List getList(String name, TypeToken elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getList(String name, Class elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getInt(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public InetAddress getInet(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public float getFloat(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public double getDouble(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public BigDecimal getDecimal(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public LocalDate getDate(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytesUnsafe(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytes(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public byte getByte(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean getBool(String name) { + // TODO Auto-generated method stub + return false; + } + + @Override + public T get(String name, TypeCodec codec) { + // TODO Auto-generated method stub + return null; + } + + @Override + public T get(String name, TypeToken targetType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public T get(String name, Class targetClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isNull(int i) { + // TODO Auto-generated method stub + return false; + } + + @Override + public BigInteger getVarint(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UUID getUUID(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UDTValue getUDTValue(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public TupleValue getTupleValue(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Date getTimestamp(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getTime(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getString(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public short getShort(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public Set getSet(int i, TypeToken elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getSet(int i, Class elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getObject(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getMap(int i, TypeToken keysType, TypeToken valuesType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getMap(int i, Class keysClass, Class valuesClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getLong(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public List getList(int i, TypeToken elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getList(int i, Class elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getInt(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public InetAddress getInet(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public float getFloat(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public double getDouble(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public BigDecimal getDecimal(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public LocalDate getDate(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytesUnsafe(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytes(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public byte getByte(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean getBool(int i) { + // TODO Auto-generated method stub + return false; + } + + @Override + public T get(int i, TypeCodec codec) { + // TODO Auto-generated method stub + return null; + } + + @Override + public T get(int i, TypeToken targetType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public T get(int i, Class targetClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getToken(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getToken(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getPartitionKeyToken() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ColumnDefinitions getColumnDefinitions() { + // TODO Auto-generated method stub + return null; + } + }; + return row; + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java new file mode 100644 index 00000000..44c72763 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java @@ -0,0 +1,225 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.batch.helpers.Approval; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; +import org.onap.aaf.auth.dao.cass.ApprovalDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.LogTarget; + +import junit.framework.Assert; + +public class JU_Approval { + + Approval approval; + UUID id; + UUID ticket; + Date date; + + @Before + public void setUp() { + id = new UUID(0, 0); + ticket = new UUID(0, 0); + date = new Date(); + + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + } + + @Test + public void testRoleFromMemo() { + Assert.assertNull(approval.roleFromMemo(null)); + Assert.assertEquals(".admin", + approval.roleFromMemo("Re-Validate as Administrator for AAF Namespace '\'test\'test")); + Assert.assertEquals(".owner", approval.roleFromMemo("Re-Validate Ownership for AAF Namespace '\'test\'test")); + Assert.assertEquals("", approval.roleFromMemo("Re-Approval in Role '\'test\'test")); + } + + @Test + public void testExpunge() { + approval.expunge(); + } + + @Test + public void testGetLast_notified() { + Assert.assertTrue(approval.getLast_notified() instanceof Date); + } + + @Test + public void testSetLastNotified() { + approval.setLastNotified(date); + } + + @Test + public void testGetStatus() { + Assert.assertEquals("status", approval.getStatus()); + } + + @Test + public void testSetStatus() { + approval.setStatus("status"); + } + + @Test + public void testGetId() { + Assert.assertTrue(approval.getId() instanceof UUID); + } + + @Test + public void testGetTicket() { + Assert.assertTrue(approval.getTicket() instanceof UUID); + } + + @Test + public void testGetMemo() { + Assert.assertEquals("memo", approval.getMemo()); + } + + @Test + public void testGetOperation() { + Assert.assertEquals("operation", approval.getOperation()); + } + + @Test + public void testGetType() { + Assert.assertEquals("type", approval.getType()); + } + + @Test + public void testLapsed() { + approval.lapsed(); + } + + @Test + public void testGetRole() { + Assert.assertNull(approval.getRole()); + } + + @Test + public void testToString() { + Assert.assertEquals("user memo", approval.toString()); + } + + @Test + public void testResetLocalData() { + approval.resetLocalData(); + } + + @Test + public void testPendingDelete() { + Assert.assertFalse(approval.pendingDelete(approval)); + } + + @Test + public void testUpdateNonDryRun() { + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + approval.update(trans, dao, false); + } + + @Test + public void testUpdateDryRun() { + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + approval.update(trans, dao, true); + } + + @Test + public void testDelayDeleteDryRun() { + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + List list = new ArrayList(); + list.add(approval); + Approval.delayDelete(trans, dao, true, list, "text"); + } + + @Test + public void testDelayDeleteNonDryRun() { + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + Result rv = Result.ok(); + when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); + + List list = new ArrayList(); + list.add(approval); + Approval.delayDelete(trans, dao, false, list, "text"); + } + + @Test + public void testDelayDeleteResultNotOk() { + approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + Result rv = Result.err(new Exception()); + when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); + + List list = new ArrayList(); + list.add(approval); + Approval.delayDelete(trans, dao, false, list, "text"); + } + + @Test + public void testv2() { + Approval.v2_0_17.create(RowCreator.getRow()); + + assertEquals( + "select id,ticket,approver,last_notified,user,memo,operation,status,type,WRITETIME(status) from authz.approval", + Approval.v2_0_17.select()); + + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approver.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approver.java new file mode 100644 index 00000000..bd498f58 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approver.java @@ -0,0 +1,65 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.batch.helpers.Approver; +import org.onap.aaf.auth.org.Organization; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_Approver { + + Approver approver; + Organization org; + Message msg; + + @Before + public void setUp() { + org = mock(Organization.class); + approver = new Approver("approver", org); + msg = new Message(); + } + + @Test + public void testAddRequest() { + approver.addRequest("user"); + approver.addRequest("user"); + } + + @Test + public void testBuild() { + approver.addRequest("user"); + approver.addRequest("user1"); + approver.addRequest("user2"); + approver.addRequest("user3"); + approver.build(msg); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_CacheChange.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_CacheChange.java new file mode 100644 index 00000000..27d2d3cc --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_CacheChange.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.CacheChange; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.util.List; + +import org.junit.Test; + +public class JU_CacheChange { + + CacheChange cc; + + + @Before + public void setUp() { + cc = new CacheChange(); + } + + @Test + public void testDelayedDelete() { + cc.delayedDelete(null); + } + + @Test + public void testGetRemoved() { + List list = cc.getRemoved(); + Assert.assertNotNull(list); + } + + @Test + public void testResetLocalData() { + cc.resetLocalData(); + } + + @Test + public void testCacheSize() { + int size; + size = cc.cacheSize(); + Assert.assertEquals(0, size); + } + + @Test + public void testContains() { + boolean containsBools; + containsBools = cc.contains(null); + Assert.assertEquals(false, containsBools); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Creator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Creator.java new file mode 100644 index 00000000..2a266f54 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Creator.java @@ -0,0 +1,72 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.Creator; + +import com.datastax.driver.core.Row; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_Creator { + + CreatorStub creatorStub; + + private class CreatorStub extends Creator{ + + @Override + public Object create(Row row) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String select() { + // TODO Auto-generated method stub + return "Select"; //Changed from null to Select + } + + } + + @Before + public void setUp() { + creatorStub = new CreatorStub(); + } + + @Test + public void testQuery() { + creatorStub.select(); + Assert.assertEquals("Select WHERE test;", creatorStub.query("test")); + Assert.assertEquals("Select;", creatorStub.query(null)); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Cred.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Cred.java new file mode 100644 index 00000000..20831c66 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Cred.java @@ -0,0 +1,142 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.Cred; +import org.onap.aaf.auth.batch.helpers.Cred.CredCount; +import org.onap.aaf.auth.batch.helpers.Cred.Instance; +import org.onap.aaf.auth.common.Define; +import org.onap.aaf.cadi.CadiException; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.Session; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Date; + +import org.junit.Test; + +public class JU_Cred { + + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; + Cred cred; + Instance instance; + Date date; + Integer integer; + PropAccess prop; + Define define = new Define(); + Trans trans; + Session session; + CredCount cc; + + @Before + public void setUp() throws CadiException { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + date = new Date(); + integer = new Integer(20); + trans = mock(Trans.class); + session = mock(Session.class); + cc = new CredCount(3); + prop = new PropAccess(); + prop.setProperty(Config.AAF_ROOT_NS, "org.onap.aaf"); + prop.setProperty(Config.AAF_ROOT_COMPANY,"test"); + define.set(prop); + + instance = new Instance(12, date, integer, 125642678910L); + cred = new Cred("myid1234@aaf.att.com"); + } + + @Test + public void testLast() { //TODO: set instances + Assert.assertNull(cred.last(null)); + } + + @Test + public void testTypes() { //TODO: set instances + Assert.assertNotNull(cred.types()); + } + + @Test + public void testCount() { //TODO: set instances + Assert.assertNotNull(cred.count(3)); + } + + @Test + public void testToString() { //TODO: set instances + Assert.assertEquals("myid1234@aaf.att.com[]", cred.toString()); + } + + @Test + public void testHashCode() { //TODO: set instances + Assert.assertEquals(-1619358251, cred.hashCode()); + } + + @Test + public void testEquals() { //TODO: set instances + Assert.assertEquals(true, cred.equals("myid1234@aaf.att.com")); + } + + @Test + public void testInc() { + Date begin = new Date(date.getTime() - 10); + Date after = new Date(date.getTime() + 10); + cc.inc(-1, begin, after); + cc.inc(1, begin, after); + cc.inc(2, begin, after); + cc.inc(200, begin, after); + } + + @Test + public void testAuthCount() { //TODO: set instances + Assert.assertEquals(0, cc.authCount(1)); + } + + @Test + public void testX509Count() { //TODO: set instances + Assert.assertEquals(0, cc.x509Count(0)); + } + + @After + public void cleanUp() { + System.setErr(System.err); + System.setOut(System.out); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java new file mode 100644 index 00000000..4ed167e9 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java @@ -0,0 +1,71 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; + +import java.util.GregorianCalendar; +import java.util.Set; + +import org.junit.Test; +import org.onap.aaf.auth.batch.helpers.ExpireRange; +import org.onap.aaf.cadi.PropAccess; + +public class JU_ExpireRange { + @Test + public void test() { + ExpireRange expRange = new ExpireRange(new PropAccess()); + + Set names=expRange.names(); + assertTrue(names.contains("OneMonth")); + assertTrue(names.contains("CredOneWeek")); + assertTrue(names.contains("Delete")); + assertFalse(names.contains(null)); + assertFalse(names.contains("bogus")); + + ExpireRange.Range r; + GregorianCalendar gc = new GregorianCalendar(); + String[] all = new String[] {"ur","cred"}; + + // Test 3 weeks prior + gc.setTime(expRange.now); + gc.add(GregorianCalendar.WEEK_OF_MONTH,-3); + for(String rs : all) { + r = expRange.getRange(rs, gc.getTime()); + assertNotNull(r); + assertEquals("Delete",r.name()); + assertFalse(r.shouldContact(null)); + } + + // Test 1 week prior + gc.setTime(expRange.now); + gc.add(GregorianCalendar.WEEK_OF_MONTH,-1); + for(String rs : all) { + r = expRange.getRange(rs, gc.getTime()); + assertNull(r); + } + + // Test Today + r = expRange.getRange("cred", expRange.now); + assertNotNull(r); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java new file mode 100644 index 00000000..91950c66 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java @@ -0,0 +1,177 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Date; +import java.util.UUID; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.batch.helpers.Creator; +import org.onap.aaf.auth.batch.helpers.Future; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; +import org.onap.aaf.auth.dao.cass.FutureDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.layer.Result; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.LogTarget; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; + +public class JU_Future { + + Future future; + Date start; + Date expires; + ByteBuffer bBuff; + + @Before + public void setUp() { + UUID id = new UUID(0, 0); + start = new Date(); + expires = new Date(); + future = new Future(id, "Re-Validate Ownership for AAF Namespace '\'test\'test", "target", start, expires, + bBuff); + } + + @Test + public void testId() { + Assert.assertTrue(future.id() instanceof UUID); + } + + @Test + public void testMemo() { + Assert.assertEquals("Re-Validate Ownership for AAF Namespace '\'test\'test", future.memo()); + } + + @Test + public void testStart() { + Assert.assertTrue(future.start() instanceof Date); + } + + @Test + public void testExpires() { + Assert.assertTrue(future.expires() instanceof Date); + } + + @Test + public void testTarget() { + Assert.assertEquals("target", future.target()); + } + + @Test + public void testExpunge() { + future.expunge(); + } + + @Test + public void testCompareTo() { + future.compareTo(null); + future.compareTo(future); + } + + @Test + public void testResetLocalData() { + Future.resetLocalData(); + } + + @Test + public void testSizeForDeletion() { + Assert.assertEquals(0, Future.sizeForDeletion()); + } + + @Test + public void testPendingDelete() { + Assert.assertEquals(false, Future.pendingDelete(future)); + } + + @Test + public void testLoad() { + Session session = mock(Session.class); + Trans trans = mock(Trans.class); + @SuppressWarnings("unchecked") + Creator creator = (Creator)mock(Creator.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList rows = new ArrayList(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(results.all()).thenReturn(rows); + when(trans.info()).thenReturn(target); + when(trans.start("Load Futures", Env.REMOTE)).thenReturn(tt); + when(trans.start("Process Futures", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(creator.create(row)).thenReturn(future); + + Future.load(trans, session, creator); + } + + @Test + public void testV2() { + Future.v2_0_17.create(RowCreator.getRow()); + assertEquals(Future.v2_0_17.select(), "select id,memo,target,start,expires from authz.future"); + } + + @Test + public void testWithConstruct() { + Future.withConstruct.create(RowCreator.getRow()); + assertEquals(Future.withConstruct.select(), "select id,memo,target,start,expires,construct from authz.future"); + } + + @Test + public void testDelayedDeleteWithDryRun() { + AuthzTrans trans = mock(AuthzTrans.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + assertEquals(Result.ok().status, future.delayedDelete(trans, null, true, "text").status); + } + + @Test + public void testDelayedDeleteNonDryRun() { + AuthzTrans trans = mock(AuthzTrans.class); + LogTarget target = mock(LogTarget.class); + FutureDAO fd = mock(FutureDAO.class); + + when(trans.info()).thenReturn(target); + when(fd.delete(any(AuthzTrans.class), any(FutureDAO.Data.class), any(Boolean.class))).thenReturn(Result.ok()); + + assertEquals(Result.ok().status, future.delayedDelete(trans, fd, false, "text").status); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_History.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_History.java new file mode 100644 index 00000000..beaaad31 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_History.java @@ -0,0 +1,68 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.History; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.util.UUID; + +import org.junit.Test; + +public class JU_History { + + History history; + History history1; + + @Before + public void setUp() { + UUID id = new UUID(0, 0); + history = new History(id, "action", "memo", "subject", "target", "user", 5); + history1 = new History(id, "action", "memo", "reconstruct", "subject", "target", "user", 5); + } + + @Test + public void testToString() { + String result = "00000000-0000-0000-0000-000000000000 5 user, target, action, subject, memo"; + Assert.assertEquals(result, history.toString()); + } + + @Test + public void testHashCode() { + Assert.assertEquals(0, history.hashCode()); + } + + @Test + public void testEquals() { + Assert.assertFalse(history.equals(history1)); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_InputIterator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_InputIterator.java new file mode 100644 index 00000000..f30ad3cc --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_InputIterator.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.InputIterator; + +import static org.mockito.Mockito.*; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintStream; +import java.io.Reader; + +import org.junit.Test; + +public class JU_InputIterator { + + InputIterator inputIterator; + File f; + BufferedReader bReader; + PrintStream pStream; + + @Before + public void setUp() throws IOException { + f = new File("file"); + f.createNewFile(); + bReader = new BufferedReader(new FileReader(f)); + pStream = new PrintStream(f); + inputIterator = new InputIterator(bReader, pStream, "prompt", "instructions"); + } + + @Test + public void test() { + inputIterator.iterator(); + inputIterator.iterator().hasNext(); + inputIterator.iterator().next(); + inputIterator.iterator().remove(); + } + + @After + public void cleanUp() { + if (f.exists()) { + f.delete(); + } + } +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MiscID.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MiscID.java new file mode 100644 index 00000000..d8a2682c --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MiscID.java @@ -0,0 +1,97 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.BatchException; +import org.onap.aaf.auth.batch.helpers.MiscID; + +import com.datastax.driver.core.Row; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_MiscID { + + MiscID miscId; + + @Before + public void setUp() { + miscId = new MiscID(); + } + + @Test + public void testRowSet() { + Row row = mock(Row.class); + miscId.set(row); + } + + @Test + public void testStringSet() throws BatchException { + String[] strArr = {"id", "sponsor", "created", "renewal"}; + miscId.set(strArr); + } + + @Test + public void testHashcode() throws BatchException { + String[] strArr = {"id", "sponsor", "created", "renewal"}; + miscId.set(strArr); + Assert.assertEquals(3355, miscId.hashCode()); + } + + @Test + public void testEquals() throws BatchException { + String[] strArr = {"id", "sponsor", "created", "renewal"}; + miscId.set(strArr); + Assert.assertFalse(miscId.equals("id")); + Assert.assertTrue(miscId.equals(miscId)); + } + + @Test + public void testInsertStmt() throws IllegalArgumentException, IllegalAccessException { + String expected = "INSERT INTO authz.miscid (id,created,sponsor,renewal) VALUES ('null','null','null','null')"; + String result = miscId.insertStmt().toString(); + Assert.assertEquals(expected, result); + } + + @Test + public void testUpdateStmt() throws IllegalArgumentException, IllegalAccessException, BatchException { + String expected = "UPDATE authz.miscid SET sponser='sponsor1',created='created1',renewal='renewal1' WHERE id='id'"; + String[] strArr = {"id", "sponsor", "created", "renewal"}; + miscId.set(strArr); + MiscID miscId1 = new MiscID(); + String[] strArr1 = {"id", "sponsor1", "created1", "renewal1"}; + miscId1.set(strArr1); + StringBuilder result = miscId.updateStmt(miscId1); + + Assert.assertEquals(expected, result.toString()); + } + + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MonthData.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MonthData.java new file mode 100644 index 00000000..d9d9d018 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_MonthData.java @@ -0,0 +1,105 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.MonthData; +import org.onap.aaf.auth.batch.helpers.MonthData.Row; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import org.junit.Test; + +public class JU_MonthData { + + File f; + MonthData mData; + Row row; + BufferedWriter bw = null; + FileWriter fw = null; + + @Before + public void setUp() throws IOException { + mData = new MonthData("env"); + row = new Row("target", 10,2,1); + f = new File("Monthlyenv.dat"); + f.createNewFile(); + bw = new BufferedWriter(new FileWriter(f)); + bw.write("#test"+ "\n"); + bw.write("long,tester"+ "\n"); + bw.write("1,2,3,4,5"+ "\n"); + bw.close(); + + mData = new MonthData("env"); + } + + @Test + public void testAdd() { + mData.add(2, "target", 10, 1, 1); + } + + @Test + public void testNotExists() { + mData.notExists(2); + } + + @Test + public void testWrite() throws IOException { + mData.write(); + } + + @Test + public void testCompareTo() { + Row testrow = new Row("testtar",1,1,1); + Assert.assertEquals(-4, row.compareTo(testrow)); + Assert.assertEquals(0, row.compareTo(row)); + } + + @Test + public void testToString() { + Assert.assertEquals("target|10|1|2", row.toString()); + } + + @After + public void cleanUp() { + File g = new File("Monthlyenv.dat.bak"); + if (f.exists()) { + f.delete(); + } + if (g.exists()) { + g.delete(); + } + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java new file mode 100644 index 00000000..1208ba92 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java @@ -0,0 +1,159 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.batch.helpers.Creator; +import org.onap.aaf.auth.batch.helpers.NS; +import org.onap.aaf.auth.batch.helpers.NS.NSSplit; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.LogTarget; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; + +import junit.framework.Assert; + +public class JU_NS { + + NS ns; + NSSplit nSSplit; + + @Before + public void setUp() { + ns = new NS("name", "description", "parent", 1, 1); + nSSplit = new NSSplit("string", 1); + } + + @Test + public void testToString() { + Assert.assertEquals("name", ns.toString()); + } + + @Test + public void testHashCode() { + Assert.assertEquals(3373707, ns.hashCode()); + } + + @Test + public void testEquals() { + Assert.assertEquals(true, ns.equals("name")); + Assert.assertEquals(false, ns.equals("name1")); + } + + @Test + public void testCompareTo() { + NS nsValid = new NS("name", "description", "parent", 1, 1); + Assert.assertEquals(0, ns.compareTo(nsValid)); + + NS nsInvalid = new NS("name1", "description", "parent", 1, 1); + Assert.assertEquals(-1, ns.compareTo(nsInvalid)); + } + + @Test + public void testDeriveParent() { + ns.deriveParent("d.ot.te.d"); + } + + @Test + public void testLoadWithoutNS() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + Creator creator = mock(Creator.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList rows = new ArrayList(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + when(creator.create(row)).thenReturn(ns); + + NS.load(trans, session, creator); + } + + @Test + public void testLoadOne() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + Creator creator = mock(Creator.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList rows = new ArrayList(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + when(creator.create(row)).thenReturn(ns); + + NS.loadOne(trans, session, creator, "text"); + } + + @Test + public void testCount() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList rows = new ArrayList(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Count Namespaces", Env.REMOTE)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.one()).thenReturn(row); + + assertEquals(0, NS.count(trans, session)); + } + + @Test + public void testV2() { + NS.v2_0_11.create(RowCreator.getRow()); + assertEquals(NS.v2_0_11.select(), "SELECT name, description, parent, type, scope FROM authz.ns "); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NsAttrib.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NsAttrib.java new file mode 100644 index 00000000..6df877fe --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NsAttrib.java @@ -0,0 +1,51 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.batch.helpers.NsAttrib; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; + +import junit.framework.Assert; + +public class JU_NsAttrib { + + NsAttrib nsAttrib; + + @Before + public void setUp() { + nsAttrib = new NsAttrib("ns", "key", "value"); + } + + @Test + public void testToString() { + Assert.assertEquals("\"ns\",\"key\",\"value\"", nsAttrib.toString()); + } + + @Test + public void testV2() { + NsAttrib.v2_0_11.create(RowCreator.getRow()); + Assert.assertEquals("select ns,key,value from authz.ns_attrib", NsAttrib.v2_0_11.select()); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Perm.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Perm.java new file mode 100644 index 00000000..10cbd359 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Perm.java @@ -0,0 +1,98 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.Perm; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +public class JU_Perm { + + Perm perm; + Set set; + + @Before + public void setUp() { + set = new HashSet(); + perm = new Perm("ns","type", "instance", "action","description", set); + } + + @Test + public void testFullType() { + Assert.assertEquals("ns.type", perm.fullType()); + } + + @Test + public void testFullPerm() { + Assert.assertEquals("ns.type|instance|action", perm.fullPerm()); + } + + @Test + public void testEncode() { + Assert.assertEquals("ns|type|instance|action", perm.encode()); + } + + @Test + public void testHashCode() { + Assert.assertEquals(850667666, perm.hashCode()); + } + + @Test + public void testToString() { + Assert.assertEquals("ns|type|instance|action", perm.toString()); + } + + @Test + public void testEquals() { + Perm perm1 = new Perm("ns","type", "instance", "action","description", set); + Assert.assertEquals(false, perm.equals(perm1)); + } + + @Test + public void testCompareTo() { + Perm perm1 = new Perm("ns","type", "instance", "action","description", set); + Perm perm2 = new Perm("ns1","type", "instance", "action","description", set); + + Assert.assertEquals(0, perm.compareTo(perm1)); + Assert.assertEquals(75, perm.compareTo(perm2)); + } + + @Test + public void testStageRemove() { + Perm perm1 = new Perm("ns","type", "instance", "action","description", set); + perm.stageRemove(perm1); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Role.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Role.java new file mode 100644 index 00000000..250c7a10 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Role.java @@ -0,0 +1,94 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.helpers.Perm; +import org.onap.aaf.auth.batch.helpers.Role; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +public class JU_Role { + + Role shortRole; + Role longRole; + Set set; + + @Before + public void setUp() { + set = new HashSet(); + shortRole = new Role("full"); + longRole = new Role("ns", "name", "description", set); + } + + @Test + public void testEncode() { + Assert.assertEquals("ns|name", longRole.encode()); + } + + @Test + public void testFullName() { + Assert.assertEquals("ns.name", longRole.fullName()); + Assert.assertEquals("full", shortRole.fullName()); + + longRole.fullName("test"); + } + + @Test + public void testToString() { + Assert.assertEquals("ns|name", longRole.toString()); + } + + @Test + public void testHashCode() { + Assert.assertEquals(-2043567518, longRole.hashCode()); + } + + @Test + public void testEquals() { + Assert.assertEquals(false, longRole.equals(longRole)); + } + + @Test + public void testCompareTo() { + Assert.assertEquals(-14, longRole.compareTo(shortRole)); + Assert.assertEquals(14, shortRole.compareTo(longRole)); + } + + @Test + public void testStageRemove() { + longRole.stageRemove(shortRole); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java new file mode 100644 index 00000000..6b7011c6 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java @@ -0,0 +1,186 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.helpers.test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aaf.auth.batch.actions.URDelete; +import org.onap.aaf.auth.batch.helpers.Creator; +import org.onap.aaf.auth.batch.helpers.UserRole; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; +import org.onap.aaf.auth.dao.cass.UserRoleDAO; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.LogTarget; +import org.onap.aaf.misc.env.TimeTaken; +import org.onap.aaf.misc.env.Trans; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; + +import junit.framework.Assert; + +public class JU_UserRole { + + UserRole userRole; + UserRole userRole1; + Date date; + PrintStream ds; + + @Before + public void setUp() { + date = new Date(); + userRole = new UserRole("user", "ns", "rname", date); + userRole = new UserRole("user", "role", "ns", "rname", date); + } + + @Test + public void testTotalLoaded() { + Assert.assertEquals(0, userRole.totalLoaded()); + } + + @Test + public void testDeleted() { + Assert.assertEquals(0, userRole.deleted()); + } + + @Test + public void testExpunge() { + userRole.expunge(); + } + + @Test + public void testSetDeleteStream() { + userRole.setDeleteStream(ds); + } + + @Test + public void testSetRecoverStream() { + userRole.setRecoverStream(ds); + } + + @Test + public void testUrdd() { + Assert.assertTrue(userRole.urdd() instanceof UserRoleDAO.Data); + } + + @Test + public void testUser() { + Assert.assertEquals("user", userRole.user()); + } + + @Test + public void testRole() { + Assert.assertEquals("role", userRole.role()); + } + + @Test + public void testNs() { + Assert.assertEquals("ns", userRole.ns()); + } + + @Test + public void testRName() { + Assert.assertEquals("rname", userRole.rname()); + } + + @Test + public void testExpires() { + Assert.assertEquals(date, userRole.expires()); + userRole.expires(date); + } + + @Test + public void testToString() { + Assert.assertTrue(userRole.toString() instanceof String); + } + + @Test + public void testGet() { + userRole.get("u", "r"); + } + + @Test + public void testResetLocalData() { + userRole.resetLocalData(); + } + + @Test + public void testSizeForDeletion() { + Assert.assertEquals(0, userRole.sizeForDeletion()); + } + + @Test + public void testPendingDelete() { + Assert.assertFalse(userRole.pendingDelete(userRole)); + } + + @Test + public void testActuateDeletionNow() { + AuthzTrans trans = mock(AuthzTrans.class); + URDelete urd = mock(URDelete.class); + userRole.actuateDeletionNow(trans, urd); + } + + @Test + public void testV2() { + UserRole.v2_0_11.create(RowCreator.getRow()); + assertEquals("select user,role,ns,rname,expires from authz.user_role", UserRole.v2_0_11.select()); + } + + @Test + public void testLoad() { + Creator creator = mock(Creator.class); + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + + List rows = new ArrayList(); + + when(trans.info()).thenReturn(target); + when(trans.start("Read UserRoles", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load UserRole", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + + List list = new ArrayList(); + list.add(RowCreator.getRow()); + list.add(RowCreator.getRow()); + + UserRole.load(trans, session, creator, new UserRole.DataLoadVisitor()); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_Batch.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_Batch.java new file mode 100644 index 00000000..1ef6f3b8 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_Batch.java @@ -0,0 +1,92 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.Batch; +import org.onap.aaf.auth.env.AuthzEnv; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.Organization; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.auth.org.OrganizationFactory; +import org.onap.aaf.cadi.client.Future; +import org.onap.aaf.cadi.client.Rcli; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.misc.env.APIException; + +import static org.mockito.Mockito.*; + +import java.io.IOException; + +import org.junit.Test; + +public class JU_Batch { + + AuthzEnv env; + Batch batch; + + private class BatchStub extends Batch { + + protected BatchStub(AuthzEnv env) throws APIException, IOException, OrganizationException { + super(env); + // TODO Auto-generated constructor stub + } + + @Override + protected void run(AuthzTrans trans) { + // TODO Auto-generated method stub + + } + + @Override + protected void _close(AuthzTrans trans) { + // TODO Auto-generated method stub + + } + + } + + @Before + public void setUp() throws OrganizationException { + env = new AuthzEnv(); + env.access().setProperty(Config.CADI_LATITUDE, "38.550674"); + env.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); + env.setProperty("DRY_RUN", "test"); + env.setProperty("Organization.@aaf.com", "test"); + //env.setProperty("Organization.com.@aaf", "java.lang.Integer"); + env.setProperty("Organization.com.@aaf", "org.onap.aaf.auth.org.Organization"); + env.setProperty("CASS_ENV", "test"); + env.setProperty("test.VERSION", "test.VERSION"); + } + + @Test + public void testIsSpecial() throws APIException, IOException, OrganizationException { + //BatchStub bStub = new BatchStub(env); + //bStub.isSpecial("user"); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchException.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchException.java new file mode 100644 index 00000000..47a7c278 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchException.java @@ -0,0 +1,59 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + + +package org.onap.aaf.auth.batch.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.BatchException; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_BatchException { + + BatchException bExcept1; + BatchException bExcept2; + BatchException bExcept3; + BatchException bExcept4; + BatchException bExcept5; + Throwable throwable; + + @Before + public void setUp() { + throwable = new Throwable(); + } + + @Test + public void testBatchException() { + bExcept1 = new BatchException(); + bExcept2 = new BatchException("test"); + bExcept3 = new BatchException(throwable); + bExcept4 = new BatchException("test", throwable); + bExcept5 = new BatchException("test", throwable,true,true); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchPrincipal.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchPrincipal.java new file mode 100644 index 00000000..4e5ad675 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_BatchPrincipal.java @@ -0,0 +1,48 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.BatchPrincipal; + +import junit.framework.Assert; + +import static org.mockito.Mockito.*; +import org.junit.Test; + +public class JU_BatchPrincipal { + + BatchPrincipal bPrincipal; + + @Test + public void testBatchPrincipal() { + bPrincipal = new BatchPrincipal("name"); + Assert.assertEquals("batch:name", bPrincipal.getName()); + Assert.assertEquals("Btch", bPrincipal.tag()); + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_CassBatch.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_CassBatch.java new file mode 100644 index 00000000..dfb30819 --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_CassBatch.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ + +package org.onap.aaf.auth.batch.test; + +import static org.junit.Assert.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aaf.auth.batch.CassBatch; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.auth.org.OrganizationException; +import org.onap.aaf.misc.env.APIException; + +import static org.mockito.Mockito.*; + +import java.io.IOException; + +import org.junit.Test; + +public class JU_CassBatch { + + AuthzTrans aTrans; + + private class CassBatchStub extends CassBatch { + + protected CassBatchStub(AuthzTrans trans, String log4jName) + throws APIException, IOException, OrganizationException { + super(trans, log4jName); + // TODO Auto-generated constructor stub + } + + @Override + protected void run(AuthzTrans trans) { + // TODO Auto-generated method stub + + } + + } + + @Before + public void setUp() throws APIException, IOException, OrganizationException { + aTrans = mock(AuthzTrans.class); + //CassBatchStub cassBatchStub = new CassBatchStub(aTrans,"log"); //Cannot do until Batch is understood + } + +} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_NotificationTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_NotificationTest.java new file mode 100644 index 00000000..79e4168e --- /dev/null +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/test/JU_NotificationTest.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START==================================================== + * org.onap.aaf + * =========================================================================== + * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. + * =========================================================================== + * 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. + * ============LICENSE_END==================================================== + * + */ +package org.onap.aaf.auth.batch.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aaf.auth.batch.actions.Message; +import org.onap.aaf.auth.batch.helpers.Creator; +import org.onap.aaf.auth.batch.helpers.Notification; +import org.onap.aaf.auth.batch.helpers.Notification.TYPE; +import org.onap.aaf.auth.batch.helpers.creators.RowCreator; +import org.onap.aaf.auth.env.AuthzTrans; +import org.onap.aaf.misc.env.Env; +import org.onap.aaf.misc.env.LogTarget; +import org.onap.aaf.misc.env.TimeTaken; + +public class JU_NotificationTest { + + @Mock + private AuthzTrans trans; + @Mock + private Creator creator; + @Mock + private TimeTaken tt; + + @Mock + private LogTarget logTarget; + private Message msg; + + @Before + public void setUp() throws Exception { + initMocks(this); + + msg = new Message(); + msg.line("%n", "Message"); + + when(trans.info()).thenReturn(logTarget); + when(trans.start("Load Notify", Env.REMOTE)).thenReturn(tt); + } + + @Test + public void test() { + Notification notification = Notification.create("user", TYPE.CN); + assertEquals(notification.checksum(), 0); + notification.set(msg); + assertEquals(notification.checksum(), 10); + assertNull(Notification.get("user", TYPE.CN)); + assertTrue(notification.update(trans, null, true)); + assertTrue(notification.toString().contains("\"user\",\"CN\",")); + + Notification.v2_0_18.create(RowCreator.getRow()); + assertEquals(Notification.v2_0_18.select(), "SELECT user,type,last,checksum FROM authz.notify LIMIT 100000"); + + } +} \ No newline at end of file diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/JU_NotificationTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/JU_NotificationTest.java deleted file mode 100644 index d3a1258d..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/JU_NotificationTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ -package org.onap.aaf.auth.helpers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Notification.TYPE; -import org.onap.aaf.auth.helpers.creators.RowCreator; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.TimeTaken; - -public class JU_NotificationTest { - - @Mock - private AuthzTrans trans; - @Mock - private Creator creator; - @Mock - private TimeTaken tt; - - @Mock - private LogTarget logTarget; - private Message msg; - - @Before - public void setUp() throws Exception { - initMocks(this); - - msg = new Message(); - msg.line("%n", "Message"); - - when(trans.info()).thenReturn(logTarget); - when(trans.start("Load Notify", Env.REMOTE)).thenReturn(tt); - } - - @Test - public void test() { - Notification notification = Notification.create("user", TYPE.CN); - assertEquals(notification.checksum(), 0); - notification.set(msg); - assertEquals(notification.checksum(), 10); - assertNull(Notification.get("user", TYPE.CN)); - assertTrue(notification.update(trans, null, true)); - assertTrue(notification.toString().contains("\"user\",\"CN\",")); - - Notification.v2_0_18.create(RowCreator.getRow()); - assertEquals(Notification.v2_0_18.select(), "SELECT user,type,last,checksum FROM authz.notify LIMIT 100000"); - - } -} \ No newline at end of file diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/creators/RowCreator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/creators/RowCreator.java deleted file mode 100644 index 078c383b..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/creators/RowCreator.java +++ /dev/null @@ -1,434 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ -package org.onap.aaf.auth.helpers.creators; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.InetAddress; -import java.nio.ByteBuffer; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.LocalDate; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Token; -import com.datastax.driver.core.TupleValue; -import com.datastax.driver.core.TypeCodec; -import com.datastax.driver.core.UDTValue; -import com.google.common.reflect.TypeToken; - -public class RowCreator { - - public static Row getRow() { - Row row = new Row() { - - @Override - public boolean isNull(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public BigInteger getVarint(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UUID getUUID(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UDTValue getUDTValue(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TupleValue getTupleValue(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getTimestamp(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getTime(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getString(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public short getShort(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Set getSet(String name, TypeToken elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getSet(String name, Class elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getObject(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getMap(String name, TypeToken keysType, TypeToken valuesType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getMap(String name, Class keysClass, Class valuesClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getLong(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public List getList(String name, TypeToken elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getList(String name, Class elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getInt(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public InetAddress getInet(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public float getFloat(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public double getDouble(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public BigDecimal getDecimal(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public LocalDate getDate(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytesUnsafe(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytes(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public byte getByte(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public boolean getBool(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public T get(String name, TypeCodec codec) { - // TODO Auto-generated method stub - return null; - } - - @Override - public T get(String name, TypeToken targetType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public T get(String name, Class targetClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isNull(int i) { - // TODO Auto-generated method stub - return false; - } - - @Override - public BigInteger getVarint(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UUID getUUID(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UDTValue getUDTValue(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TupleValue getTupleValue(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Date getTimestamp(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getTime(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getString(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public short getShort(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Set getSet(int i, TypeToken elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getSet(int i, Class elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getObject(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getMap(int i, TypeToken keysType, TypeToken valuesType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getMap(int i, Class keysClass, Class valuesClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getLong(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public List getList(int i, TypeToken elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getList(int i, Class elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getInt(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public InetAddress getInet(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public float getFloat(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public double getDouble(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public BigDecimal getDecimal(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public LocalDate getDate(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytesUnsafe(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytes(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public byte getByte(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public boolean getBool(int i) { - // TODO Auto-generated method stub - return false; - } - - @Override - public T get(int i, TypeCodec codec) { - // TODO Auto-generated method stub - return null; - } - - @Override - public T get(int i, TypeToken targetType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public T get(int i, Class targetClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getToken(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getToken(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getPartitionKeyToken() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ColumnDefinitions getColumnDefinitions() { - // TODO Auto-generated method stub - return null; - } - }; - return row; - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approval.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approval.java deleted file mode 100644 index 6020dcc0..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approval.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aaf.auth.dao.cass.ApprovalDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Approval; -import org.onap.aaf.auth.helpers.creators.RowCreator; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.LogTarget; - -import junit.framework.Assert; - -public class JU_Approval { - - Approval approval; - UUID id; - UUID ticket; - Date date; - - @Before - public void setUp() { - id = new UUID(0, 0); - ticket = new UUID(0, 0); - date = new Date(); - - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - } - - @Test - public void testRoleFromMemo() { - Assert.assertNull(approval.roleFromMemo(null)); - Assert.assertEquals(".admin", - approval.roleFromMemo("Re-Validate as Administrator for AAF Namespace '\'test\'test")); - Assert.assertEquals(".owner", approval.roleFromMemo("Re-Validate Ownership for AAF Namespace '\'test\'test")); - Assert.assertEquals("", approval.roleFromMemo("Re-Approval in Role '\'test\'test")); - } - - @Test - public void testExpunge() { - approval.expunge(); - } - - @Test - public void testGetLast_notified() { - Assert.assertTrue(approval.getLast_notified() instanceof Date); - } - - @Test - public void testSetLastNotified() { - approval.setLastNotified(date); - } - - @Test - public void testGetStatus() { - Assert.assertEquals("status", approval.getStatus()); - } - - @Test - public void testSetStatus() { - approval.setStatus("status"); - } - - @Test - public void testGetId() { - Assert.assertTrue(approval.getId() instanceof UUID); - } - - @Test - public void testGetTicket() { - Assert.assertTrue(approval.getTicket() instanceof UUID); - } - - @Test - public void testGetMemo() { - Assert.assertEquals("memo", approval.getMemo()); - } - - @Test - public void testGetOperation() { - Assert.assertEquals("operation", approval.getOperation()); - } - - @Test - public void testGetType() { - Assert.assertEquals("type", approval.getType()); - } - - @Test - public void testLapsed() { - approval.lapsed(); - } - - @Test - public void testGetRole() { - Assert.assertNull(approval.getRole()); - } - - @Test - public void testToString() { - Assert.assertEquals("user memo", approval.toString()); - } - - @Test - public void testResetLocalData() { - approval.resetLocalData(); - } - - @Test - public void testPendingDelete() { - Assert.assertFalse(approval.pendingDelete(approval)); - } - - @Test - public void testUpdateNonDryRun() { - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - approval.update(trans, dao, false); - } - - @Test - public void testUpdateDryRun() { - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - approval.update(trans, dao, true); - } - - @Test - public void testDelayDeleteDryRun() { - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - List list = new ArrayList(); - list.add(approval); - Approval.delayDelete(trans, dao, true, list, "text"); - } - - @Test - public void testDelayDeleteNonDryRun() { - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - Result rv = Result.ok(); - when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); - - List list = new ArrayList(); - list.add(approval); - Approval.delayDelete(trans, dao, false, list, "text"); - } - - @Test - public void testDelayDeleteResultNotOk() { - approval = new Approval(id, ticket, "approver", date, "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - Result rv = Result.err(new Exception()); - when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); - - List list = new ArrayList(); - list.add(approval); - Approval.delayDelete(trans, dao, false, list, "text"); - } - - @Test - public void testv2() { - Approval.v2_0_17.create(RowCreator.getRow()); - - assertEquals( - "select id,ticket,approver,last_notified,user,memo,operation,status,type,WRITETIME(status) from authz.approval", - Approval.v2_0_17.select()); - - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approver.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approver.java deleted file mode 100644 index b4ae1213..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Approver.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.actions.Message; -import org.onap.aaf.auth.helpers.Approver; -import org.onap.aaf.auth.org.Organization; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_Approver { - - Approver approver; - Organization org; - Message msg; - - @Before - public void setUp() { - org = mock(Organization.class); - approver = new Approver("approver", org); - msg = new Message(); - } - - @Test - public void testAddRequest() { - approver.addRequest("user"); - approver.addRequest("user"); - } - - @Test - public void testBuild() { - approver.addRequest("user"); - approver.addRequest("user1"); - approver.addRequest("user2"); - approver.addRequest("user3"); - approver.build(msg); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_CacheChange.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_CacheChange.java deleted file mode 100644 index fc934e6c..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_CacheChange.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.CacheChange; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.util.List; - -import org.junit.Test; - -public class JU_CacheChange { - - CacheChange cc; - - - @Before - public void setUp() { - cc = new CacheChange(); - } - - @Test - public void testDelayedDelete() { - cc.delayedDelete(null); - } - - @Test - public void testGetRemoved() { - List list = cc.getRemoved(); - Assert.assertNotNull(list); - } - - @Test - public void testResetLocalData() { - cc.resetLocalData(); - } - - @Test - public void testCacheSize() { - int size; - size = cc.cacheSize(); - Assert.assertEquals(0, size); - } - - @Test - public void testContains() { - boolean containsBools; - containsBools = cc.contains(null); - Assert.assertEquals(false, containsBools); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Creator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Creator.java deleted file mode 100644 index ad4d2022..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Creator.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.Creator; - -import com.datastax.driver.core.Row; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_Creator { - - CreatorStub creatorStub; - - private class CreatorStub extends Creator{ - - @Override - public Object create(Row row) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String select() { - // TODO Auto-generated method stub - return "Select"; //Changed from null to Select - } - - } - - @Before - public void setUp() { - creatorStub = new CreatorStub(); - } - - @Test - public void testQuery() { - creatorStub.select(); - Assert.assertEquals("Select WHERE test;", creatorStub.query("test")); - Assert.assertEquals("Select;", creatorStub.query(null)); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Cred.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Cred.java deleted file mode 100644 index 35a63059..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Cred.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.common.Define; -import org.onap.aaf.auth.helpers.Cred; -import org.onap.aaf.auth.helpers.Cred.CredCount; -import org.onap.aaf.auth.helpers.Cred.Instance; -import org.onap.aaf.cadi.CadiException; -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.config.Config; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.Session; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.Date; - -import org.junit.Test; - -public class JU_Cred { - - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; - Cred cred; - Instance instance; - Date date; - Integer integer; - PropAccess prop; - Define define = new Define(); - Trans trans; - Session session; - CredCount cc; - - @Before - public void setUp() throws CadiException { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - date = new Date(); - integer = new Integer(20); - trans = mock(Trans.class); - session = mock(Session.class); - cc = new CredCount(3); - prop = new PropAccess(); - prop.setProperty(Config.AAF_ROOT_NS, "org.onap.aaf"); - prop.setProperty(Config.AAF_ROOT_COMPANY,"test"); - define.set(prop); - - instance = new Instance(12, date, integer, 125642678910L); - cred = new Cred("myid1234@aaf.att.com"); - } - - @Test - public void testLast() { //TODO: set instances - Assert.assertNull(cred.last(null)); - } - - @Test - public void testTypes() { //TODO: set instances - Assert.assertNotNull(cred.types()); - } - - @Test - public void testCount() { //TODO: set instances - Assert.assertNotNull(cred.count(3)); - } - - @Test - public void testToString() { //TODO: set instances - Assert.assertEquals("myid1234@aaf.att.com[]", cred.toString()); - } - - @Test - public void testHashCode() { //TODO: set instances - Assert.assertEquals(-1619358251, cred.hashCode()); - } - - @Test - public void testEquals() { //TODO: set instances - Assert.assertEquals(true, cred.equals("myid1234@aaf.att.com")); - } - - @Test - public void testInc() { - Date begin = new Date(date.getTime() - 10); - Date after = new Date(date.getTime() + 10); - cc.inc(-1, begin, after); - cc.inc(1, begin, after); - cc.inc(2, begin, after); - cc.inc(200, begin, after); - } - - @Test - public void testAuthCount() { //TODO: set instances - Assert.assertEquals(0, cc.authCount(1)); - } - - @Test - public void testX509Count() { //TODO: set instances - Assert.assertEquals(0, cc.x509Count(0)); - } - - @After - public void cleanUp() { - System.setErr(System.err); - System.setOut(System.out); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Future.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Future.java deleted file mode 100644 index fe3d5d95..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Future.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Date; -import java.util.UUID; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onap.aaf.auth.dao.cass.FutureDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Creator; -import org.onap.aaf.auth.helpers.Future; -import org.onap.aaf.auth.helpers.creators.RowCreator; -import org.onap.aaf.auth.layer.Result; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; - -public class JU_Future { - - Future future; - Date start; - Date expires; - ByteBuffer bBuff; - - @Before - public void setUp() { - UUID id = new UUID(0, 0); - start = new Date(); - expires = new Date(); - future = new Future(id, "Re-Validate Ownership for AAF Namespace '\'test\'test", "target", start, expires, - bBuff); - } - - @Test - public void testId() { - Assert.assertTrue(future.id() instanceof UUID); - } - - @Test - public void testMemo() { - Assert.assertEquals("Re-Validate Ownership for AAF Namespace '\'test\'test", future.memo()); - } - - @Test - public void testStart() { - Assert.assertTrue(future.start() instanceof Date); - } - - @Test - public void testExpires() { - Assert.assertTrue(future.expires() instanceof Date); - } - - @Test - public void testTarget() { - Assert.assertEquals("target", future.target()); - } - - @Test - public void testExpunge() { - future.expunge(); - } - - @Test - public void testCompareTo() { - future.compareTo(null); - future.compareTo(future); - } - - @Test - public void testResetLocalData() { - Future.resetLocalData(); - } - - @Test - public void testSizeForDeletion() { - Assert.assertEquals(0, Future.sizeForDeletion()); - } - - @Test - public void testPendingDelete() { - Assert.assertEquals(false, Future.pendingDelete(future)); - } - - @Test - public void testLoad() { - Session session = mock(Session.class); - Trans trans = mock(Trans.class); - @SuppressWarnings("unchecked") - Creator creator = (Creator)mock(Creator.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList rows = new ArrayList(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(results.all()).thenReturn(rows); - when(trans.info()).thenReturn(target); - when(trans.start("Load Futures", Env.REMOTE)).thenReturn(tt); - when(trans.start("Process Futures", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(creator.create(row)).thenReturn(future); - - Future.load(trans, session, creator); - } - - @Test - public void testV2() { - Future.v2_0_17.create(RowCreator.getRow()); - assertEquals(Future.v2_0_17.select(), "select id,memo,target,start,expires from authz.future"); - } - - @Test - public void testWithConstruct() { - Future.withConstruct.create(RowCreator.getRow()); - assertEquals(Future.withConstruct.select(), "select id,memo,target,start,expires,construct from authz.future"); - } - - @Test - public void testDelayedDeleteWithDryRun() { - AuthzTrans trans = mock(AuthzTrans.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - assertEquals(Result.ok().status, future.delayedDelete(trans, null, true, "text").status); - } - - @Test - public void testDelayedDeleteNonDryRun() { - AuthzTrans trans = mock(AuthzTrans.class); - LogTarget target = mock(LogTarget.class); - FutureDAO fd = mock(FutureDAO.class); - - when(trans.info()).thenReturn(target); - when(fd.delete(any(AuthzTrans.class), any(FutureDAO.Data.class), any(Boolean.class))).thenReturn(Result.ok()); - - assertEquals(Result.ok().status, future.delayedDelete(trans, fd, false, "text").status); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_History.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_History.java deleted file mode 100644 index 3346f229..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_History.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.History; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.util.UUID; - -import org.junit.Test; - -public class JU_History { - - History history; - History history1; - - @Before - public void setUp() { - UUID id = new UUID(0, 0); - history = new History(id, "action", "memo", "subject", "target", "user", 5); - history1 = new History(id, "action", "memo", "reconstruct", "subject", "target", "user", 5); - } - - @Test - public void testToString() { - String result = "00000000-0000-0000-0000-000000000000 5 user, target, action, subject, memo"; - Assert.assertEquals(result, history.toString()); - } - - @Test - public void testHashCode() { - Assert.assertEquals(0, history.hashCode()); - } - - @Test - public void testEquals() { - Assert.assertFalse(history.equals(history1)); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java deleted file mode 100644 index 07fd65f0..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.InputIterator; - -import static org.mockito.Mockito.*; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintStream; -import java.io.Reader; - -import org.junit.Test; - -public class JU_InputIterator { - - InputIterator inputIterator; - File f; - BufferedReader bReader; - PrintStream pStream; - - @Before - public void setUp() throws IOException { - f = new File("file"); - f.createNewFile(); - bReader = new BufferedReader(new FileReader(f)); - pStream = new PrintStream(f); - inputIterator = new InputIterator(bReader, pStream, "prompt", "instructions"); - } - - @Test - public void test() { - inputIterator.iterator(); - inputIterator.iterator().hasNext(); - inputIterator.iterator().next(); - inputIterator.iterator().remove(); - } - - @After - public void cleanUp() { - if (f.exists()) { - f.delete(); - } - } -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MiscID.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MiscID.java deleted file mode 100644 index 6f44b391..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MiscID.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.BatchException; -import org.onap.aaf.auth.helpers.MiscID; - -import com.datastax.driver.core.Row; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_MiscID { - - MiscID miscId; - - @Before - public void setUp() { - miscId = new MiscID(); - } - - @Test - public void testRowSet() { - Row row = mock(Row.class); - miscId.set(row); - } - - @Test - public void testStringSet() throws BatchException { - String[] strArr = {"id", "sponsor", "created", "renewal"}; - miscId.set(strArr); - } - - @Test - public void testHashcode() throws BatchException { - String[] strArr = {"id", "sponsor", "created", "renewal"}; - miscId.set(strArr); - Assert.assertEquals(3355, miscId.hashCode()); - } - - @Test - public void testEquals() throws BatchException { - String[] strArr = {"id", "sponsor", "created", "renewal"}; - miscId.set(strArr); - Assert.assertFalse(miscId.equals("id")); - Assert.assertTrue(miscId.equals(miscId)); - } - - @Test - public void testInsertStmt() throws IllegalArgumentException, IllegalAccessException { - String expected = "INSERT INTO authz.miscid (id,created,sponsor,renewal) VALUES ('null','null','null','null')"; - String result = miscId.insertStmt().toString(); - Assert.assertEquals(expected, result); - } - - @Test - public void testUpdateStmt() throws IllegalArgumentException, IllegalAccessException, BatchException { - String expected = "UPDATE authz.miscid SET sponser='sponsor1',created='created1',renewal='renewal1' WHERE id='id'"; - String[] strArr = {"id", "sponsor", "created", "renewal"}; - miscId.set(strArr); - MiscID miscId1 = new MiscID(); - String[] strArr1 = {"id", "sponsor1", "created1", "renewal1"}; - miscId1.set(strArr1); - StringBuilder result = miscId.updateStmt(miscId1); - - Assert.assertEquals(expected, result.toString()); - } - - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java deleted file mode 100644 index 97b6c56b..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.MonthData; -import org.onap.aaf.auth.helpers.MonthData.Row; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import org.junit.Test; - -public class JU_MonthData { - - File f; - MonthData mData; - Row row; - BufferedWriter bw = null; - FileWriter fw = null; - - @Before - public void setUp() throws IOException { - mData = new MonthData("env"); - row = new Row("target", 10,2,1); - f = new File("Monthlyenv.dat"); - f.createNewFile(); - bw = new BufferedWriter(new FileWriter(f)); - bw.write("#test"+ "\n"); - bw.write("long,tester"+ "\n"); - bw.write("1,2,3,4,5"+ "\n"); - bw.close(); - - mData = new MonthData("env"); - } - - @Test - public void testAdd() { - mData.add(2, "target", 10, 1, 1); - } - - @Test - public void testNotExists() { - mData.notExists(2); - } - - @Test - public void testWrite() throws IOException { - mData.write(); - } - - @Test - public void testCompareTo() { - Row testrow = new Row("testtar",1,1,1); - Assert.assertEquals(-4, row.compareTo(testrow)); - Assert.assertEquals(0, row.compareTo(row)); - } - - @Test - public void testToString() { - Assert.assertEquals("target|10|1|2", row.toString()); - } - - @After - public void cleanUp() { - File g = new File("Monthlyenv.dat.bak"); - if (f.exists()) { - f.delete(); - } - if (g.exists()) { - g.delete(); - } - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NS.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NS.java deleted file mode 100644 index b69f8873..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NS.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aaf.auth.helpers.Creator; -import org.onap.aaf.auth.helpers.NS; -import org.onap.aaf.auth.helpers.NS.NSSplit; -import org.onap.aaf.auth.helpers.creators.RowCreator; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; - -import junit.framework.Assert; - -public class JU_NS { - - NS ns; - NSSplit nSSplit; - - @Before - public void setUp() { - ns = new NS("name", "description", "parent", 1, 1); - nSSplit = new NSSplit("string", 1); - } - - @Test - public void testToString() { - Assert.assertEquals("name", ns.toString()); - } - - @Test - public void testHashCode() { - Assert.assertEquals(3373707, ns.hashCode()); - } - - @Test - public void testEquals() { - Assert.assertEquals(true, ns.equals("name")); - Assert.assertEquals(false, ns.equals("name1")); - } - - @Test - public void testCompareTo() { - NS nsValid = new NS("name", "description", "parent", 1, 1); - Assert.assertEquals(0, ns.compareTo(nsValid)); - - NS nsInvalid = new NS("name1", "description", "parent", 1, 1); - Assert.assertEquals(-1, ns.compareTo(nsInvalid)); - } - - @Test - public void testDeriveParent() { - ns.deriveParent("d.ot.te.d"); - } - - @Test - public void testLoadWithoutNS() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - Creator creator = mock(Creator.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList rows = new ArrayList(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - when(creator.create(row)).thenReturn(ns); - - NS.load(trans, session, creator); - } - - @Test - public void testLoadOne() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - Creator creator = mock(Creator.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList rows = new ArrayList(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - when(creator.create(row)).thenReturn(ns); - - NS.loadOne(trans, session, creator, "text"); - } - - @Test - public void testCount() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList rows = new ArrayList(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Count Namespaces", Env.REMOTE)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.one()).thenReturn(row); - - assertEquals(0, NS.count(trans, session)); - } - - @Test - public void testV2() { - NS.v2_0_11.create(RowCreator.getRow()); - assertEquals(NS.v2_0_11.select(), "SELECT name, description, parent, type, scope FROM authz.ns "); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NsAttrib.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NsAttrib.java deleted file mode 100644 index acf9b478..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_NsAttrib.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aaf.auth.helpers.NsAttrib; -import org.onap.aaf.auth.helpers.creators.RowCreator; - -import junit.framework.Assert; - -public class JU_NsAttrib { - - NsAttrib nsAttrib; - - @Before - public void setUp() { - nsAttrib = new NsAttrib("ns", "key", "value"); - } - - @Test - public void testToString() { - Assert.assertEquals("\"ns\",\"key\",\"value\"", nsAttrib.toString()); - } - - @Test - public void testV2() { - NsAttrib.v2_0_11.create(RowCreator.getRow()); - Assert.assertEquals("select ns,key,value from authz.ns_attrib", NsAttrib.v2_0_11.select()); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Perm.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Perm.java deleted file mode 100644 index 0ccc77a2..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Perm.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.Perm; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Test; - -public class JU_Perm { - - Perm perm; - Set set; - - @Before - public void setUp() { - set = new HashSet(); - perm = new Perm("ns","type", "instance", "action","description", set); - } - - @Test - public void testFullType() { - Assert.assertEquals("ns.type", perm.fullType()); - } - - @Test - public void testFullPerm() { - Assert.assertEquals("ns.type|instance|action", perm.fullPerm()); - } - - @Test - public void testEncode() { - Assert.assertEquals("ns|type|instance|action", perm.encode()); - } - - @Test - public void testHashCode() { - Assert.assertEquals(850667666, perm.hashCode()); - } - - @Test - public void testToString() { - Assert.assertEquals("ns|type|instance|action", perm.toString()); - } - - @Test - public void testEquals() { - Perm perm1 = new Perm("ns","type", "instance", "action","description", set); - Assert.assertEquals(false, perm.equals(perm1)); - } - - @Test - public void testCompareTo() { - Perm perm1 = new Perm("ns","type", "instance", "action","description", set); - Perm perm2 = new Perm("ns1","type", "instance", "action","description", set); - - Assert.assertEquals(0, perm.compareTo(perm1)); - Assert.assertEquals(75, perm.compareTo(perm2)); - } - - @Test - public void testStageRemove() { - Perm perm1 = new Perm("ns","type", "instance", "action","description", set); - perm.stageRemove(perm1); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Role.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Role.java deleted file mode 100644 index 3fd9f870..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_Role.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.helpers.Perm; -import org.onap.aaf.auth.helpers.Role; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Test; - -public class JU_Role { - - Role shortRole; - Role longRole; - Set set; - - @Before - public void setUp() { - set = new HashSet(); - shortRole = new Role("full"); - longRole = new Role("ns", "name", "description", set); - } - - @Test - public void testEncode() { - Assert.assertEquals("ns|name", longRole.encode()); - } - - @Test - public void testFullName() { - Assert.assertEquals("ns.name", longRole.fullName()); - Assert.assertEquals("full", shortRole.fullName()); - - longRole.fullName("test"); - } - - @Test - public void testToString() { - Assert.assertEquals("ns|name", longRole.toString()); - } - - @Test - public void testHashCode() { - Assert.assertEquals(-2043567518, longRole.hashCode()); - } - - @Test - public void testEquals() { - Assert.assertEquals(false, longRole.equals(longRole)); - } - - @Test - public void testCompareTo() { - Assert.assertEquals(-14, longRole.compareTo(shortRole)); - Assert.assertEquals(14, shortRole.compareTo(longRole)); - } - - @Test - public void testStageRemove() { - longRole.stageRemove(shortRole); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_UserRole.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_UserRole.java deleted file mode 100644 index b20f9ded..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_UserRole.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.helpers.test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aaf.auth.actions.URDelete; -import org.onap.aaf.auth.dao.cass.UserRoleDAO; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.helpers.Creator; -import org.onap.aaf.auth.helpers.UserRole; -import org.onap.aaf.auth.helpers.creators.RowCreator; -import org.onap.aaf.misc.env.Env; -import org.onap.aaf.misc.env.LogTarget; -import org.onap.aaf.misc.env.TimeTaken; -import org.onap.aaf.misc.env.Trans; - -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; - -import junit.framework.Assert; - -public class JU_UserRole { - - UserRole userRole; - UserRole userRole1; - Date date; - PrintStream ds; - - @Before - public void setUp() { - date = new Date(); - userRole = new UserRole("user", "ns", "rname", date); - userRole = new UserRole("user", "role", "ns", "rname", date); - } - - @Test - public void testTotalLoaded() { - Assert.assertEquals(0, userRole.totalLoaded()); - } - - @Test - public void testDeleted() { - Assert.assertEquals(0, userRole.deleted()); - } - - @Test - public void testExpunge() { - userRole.expunge(); - } - - @Test - public void testSetDeleteStream() { - userRole.setDeleteStream(ds); - } - - @Test - public void testSetRecoverStream() { - userRole.setRecoverStream(ds); - } - - @Test - public void testUrdd() { - Assert.assertTrue(userRole.urdd() instanceof UserRoleDAO.Data); - } - - @Test - public void testUser() { - Assert.assertEquals("user", userRole.user()); - } - - @Test - public void testRole() { - Assert.assertEquals("role", userRole.role()); - } - - @Test - public void testNs() { - Assert.assertEquals("ns", userRole.ns()); - } - - @Test - public void testRName() { - Assert.assertEquals("rname", userRole.rname()); - } - - @Test - public void testExpires() { - Assert.assertEquals(date, userRole.expires()); - userRole.expires(date); - } - - @Test - public void testToString() { - Assert.assertTrue(userRole.toString() instanceof String); - } - - @Test - public void testGet() { - userRole.get("u", "r"); - } - - @Test - public void testResetLocalData() { - userRole.resetLocalData(); - } - - @Test - public void testSizeForDeletion() { - Assert.assertEquals(0, userRole.sizeForDeletion()); - } - - @Test - public void testPendingDelete() { - Assert.assertFalse(userRole.pendingDelete(userRole)); - } - - @Test - public void testActuateDeletionNow() { - AuthzTrans trans = mock(AuthzTrans.class); - URDelete urd = mock(URDelete.class); - userRole.actuateDeletionNow(trans, urd); - } - - @Test - public void testV2() { - UserRole.v2_0_11.create(RowCreator.getRow()); - assertEquals("select user,role,ns,rname,expires from authz.user_role", UserRole.v2_0_11.select()); - } - - @Test - public void testLoad() { - Creator creator = mock(Creator.class); - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - - List rows = new ArrayList(); - - when(trans.info()).thenReturn(target); - when(trans.start("Read UserRoles", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load UserRole", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - - List list = new ArrayList(); - list.add(RowCreator.getRow()); - list.add(RowCreator.getRow()); - - UserRole.load(trans, session, creator, new UserRole.DataLoadVisitor()); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_Batch.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_Batch.java deleted file mode 100644 index 5394c323..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_Batch.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.Batch; -import org.onap.aaf.auth.env.AuthzEnv; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.Organization; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.auth.org.OrganizationFactory; -import org.onap.aaf.cadi.client.Future; -import org.onap.aaf.cadi.client.Rcli; -import org.onap.aaf.cadi.config.Config; -import org.onap.aaf.misc.env.APIException; - -import static org.mockito.Mockito.*; - -import java.io.IOException; - -import org.junit.Test; - -public class JU_Batch { - - AuthzEnv env; - Batch batch; - - private class BatchStub extends Batch { - - protected BatchStub(AuthzEnv env) throws APIException, IOException, OrganizationException { - super(env); - // TODO Auto-generated constructor stub - } - - @Override - protected void run(AuthzTrans trans) { - // TODO Auto-generated method stub - - } - - @Override - protected void _close(AuthzTrans trans) { - // TODO Auto-generated method stub - - } - - } - - @Before - public void setUp() throws OrganizationException { - env = new AuthzEnv(); - env.access().setProperty(Config.CADI_LATITUDE, "38.550674"); - env.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); - env.setProperty("DRY_RUN", "test"); - env.setProperty("Organization.@aaf.com", "test"); - //env.setProperty("Organization.com.@aaf", "java.lang.Integer"); - env.setProperty("Organization.com.@aaf", "org.onap.aaf.auth.org.Organization"); - env.setProperty("CASS_ENV", "test"); - env.setProperty("test.VERSION", "test.VERSION"); - } - - @Test - public void testIsSpecial() throws APIException, IOException, OrganizationException { - //BatchStub bStub = new BatchStub(env); - //bStub.isSpecial("user"); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchException.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchException.java deleted file mode 100644 index c56a76c8..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchException.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - - -package org.onap.aaf.auth.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.BatchException; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_BatchException { - - BatchException bExcept1; - BatchException bExcept2; - BatchException bExcept3; - BatchException bExcept4; - BatchException bExcept5; - Throwable throwable; - - @Before - public void setUp() { - throwable = new Throwable(); - } - - @Test - public void testBatchException() { - bExcept1 = new BatchException(); - bExcept2 = new BatchException("test"); - bExcept3 = new BatchException(throwable); - bExcept4 = new BatchException("test", throwable); - bExcept5 = new BatchException("test", throwable,true,true); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchPrincipal.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchPrincipal.java deleted file mode 100644 index 6186df95..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_BatchPrincipal.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.BatchPrincipal; - -import junit.framework.Assert; - -import static org.mockito.Mockito.*; -import org.junit.Test; - -public class JU_BatchPrincipal { - - BatchPrincipal bPrincipal; - - @Test - public void testBatchPrincipal() { - bPrincipal = new BatchPrincipal("name"); - Assert.assertEquals("batch:name", bPrincipal.getName()); - Assert.assertEquals("Btch", bPrincipal.tag()); - } - -} diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_CassBatch.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_CassBatch.java deleted file mode 100644 index d1934a42..00000000 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/test/JU_CassBatch.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - * - */ - -package org.onap.aaf.auth.test; - -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.aaf.auth.CassBatch; -import org.onap.aaf.auth.env.AuthzTrans; -import org.onap.aaf.auth.org.OrganizationException; -import org.onap.aaf.misc.env.APIException; - -import static org.mockito.Mockito.*; - -import java.io.IOException; - -import org.junit.Test; - -public class JU_CassBatch { - - AuthzTrans aTrans; - - private class CassBatchStub extends CassBatch { - - protected CassBatchStub(AuthzTrans trans, String log4jName) - throws APIException, IOException, OrganizationException { - super(trans, log4jName); - // TODO Auto-generated constructor stub - } - - @Override - protected void run(AuthzTrans trans) { - // TODO Auto-generated method stub - - } - - } - - @Before - public void setUp() throws APIException, IOException, OrganizationException { - aTrans = mock(AuthzTrans.class); - //CassBatchStub cassBatchStub = new CassBatchStub(aTrans,"log"); //Cannot do until Batch is understood - } - -} diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/ExpireRange.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/ExpireRange.java deleted file mode 100644 index c21b2bef..00000000 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/ExpireRange.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - */ - -package org.onap.aaf.auth.org; - -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.onap.aaf.cadi.Access; - -public class ExpireRange { - private static final String AAF_BATCH_RANGE = "aaf_batch_range."; - public Map> ranges; - public final Date now; - - public ExpireRange(final Access access) { - now = new Date(); - ranges = new HashMap<>(); - int i=0; - String prop = access.getProperty(AAF_BATCH_RANGE + i,null); - if(prop==null) { - if(i==0) { - List lcred = getRangeList("cred"); - List lur = getRangeList("ur"); - List lx509 = getRangeList("x509"); - - Range del = new Range("Delete",0,0,-1,0,GregorianCalendar.WEEK_OF_MONTH,-2); - lur.add(del); - lcred.add(del); - lx509.add(del); - - lcred.add(new Range("CredOneWeek",3,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); - lcred.add(new Range("CredTwoWeek",2,1,GregorianCalendar.WEEK_OF_MONTH,1,GregorianCalendar.WEEK_OF_MONTH,2)); - lcred.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - lcred.add(new Range("TwoMonth",1,0,GregorianCalendar.MONTH,1,GregorianCalendar.MONTH,2)); - - lur.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - - lx509.add(new Range("OneMonth",1,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - } - } - } - - public Set names() { - Set names = new HashSet<>(); - for(List lr : ranges.values()) { - for(Range r : lr) { - names.add(r.name); - } - } - - return names; - } - - private synchronized List getRangeList(final String key) { - List rv = ranges.get(key); - if(rv==null) { - rv = new ArrayList<>(); - ranges.put(key, rv); - } - return rv; - } - - public class Range { - private final String name; - private final int reportingLevel; - private final int interval; // in Days - private final Date start; - private final Date end; - - public Range( - final String name, final int reportingLevel, final int interval, - final int startGCType, final int startQty, - final int endGCType,final int endQty) { - this.name = name; - this.reportingLevel = reportingLevel; - this.interval = interval; - GregorianCalendar gc = new GregorianCalendar(); - if(startGCType<0) { - gc.set(GregorianCalendar.YEAR, 1); - } else { - gc.setTime(now); - gc.add(startGCType, startQty); - } - start = gc.getTime(); - - if(endGCType<0) { - gc.set(GregorianCalendar.YEAR, 1); - } else { - gc.setTime(now); - gc.add(endGCType, endQty); - } - end = gc.getTime(); - } - - public String name() { - return name; - } - - public int reportingLevel() { - return reportingLevel; - } - - public Date getStart() { - return start; - } - - public Date getEnd() { - return end; - } - - private boolean inRange(final Date date) { - if(date==null) { - return false; - } else { - return date.getTime()>=start.getTime() && date.before(end); - } - } - - public boolean shouldContact(final Date lastContact) { - if(reportingLevel<=0) { - return false; - } else if(lastContact==null) { - return true; - } else if(interval==0) { - return lastContact.before(start); - } else { - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(now); - gc.add(GregorianCalendar.DAY_OF_WEEK, interval); - return lastContact.before(gc.getTime()); - } - } - } - - public Range getRange(final String key, final Date date) { - Range rv = null; - if(date!=null) { - List lr = ranges.get(key); - if(lr==null) { - return null; - } else { - for(Range r : lr) { - if(r.inRange(date)) { - rv = r; - break; - } - } - } - } - return rv; - } - - -} diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_ExpireRange.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_ExpireRange.java deleted file mode 100644 index c42cf53d..00000000 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_ExpireRange.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * ============LICENSE_START==================================================== - * org.onap.aaf - * =========================================================================== - * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. - * =========================================================================== - * 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. - * ============LICENSE_END==================================================== - */ - -package org.onap.aaf.auth.org.test; - -import static org.junit.Assert.*; - -import java.util.GregorianCalendar; -import java.util.Set; - -import org.junit.Test; -import org.onap.aaf.auth.org.ExpireRange; -import org.onap.aaf.cadi.PropAccess; - -public class JU_ExpireRange { - @Test - public void test() { - ExpireRange expRange = new ExpireRange(new PropAccess()); - - Set names=expRange.names(); - assertTrue(names.contains("OneMonth")); - assertTrue(names.contains("CredOneWeek")); - assertTrue(names.contains("Delete")); - assertFalse(names.contains(null)); - assertFalse(names.contains("bogus")); - - ExpireRange.Range r; - GregorianCalendar gc = new GregorianCalendar(); - String[] all = new String[] {"ur","cred"}; - - // Test 3 weeks prior - gc.setTime(expRange.now); - gc.add(GregorianCalendar.WEEK_OF_MONTH,-3); - for(String rs : all) { - r = expRange.getRange(rs, gc.getTime()); - assertNotNull(r); - assertEquals("Delete",r.name()); - assertFalse(r.shouldContact(null)); - } - - // Test 1 week prior - gc.setTime(expRange.now); - gc.add(GregorianCalendar.WEEK_OF_MONTH,-1); - for(String rs : all) { - r = expRange.getRange(rs, gc.getTime()); - assertNull(r); - } - - // Test Today - r = expRange.getRange("cred", expRange.now); - assertNotNull(r); - } - -} -- cgit 1.2.3-korg